Debian Codegraph @

js/src/jit-test/tests/warp/string-startswith-constant-string.js

raw
1 // Test case to cover String.prototype.startsWith with a constant search string.
2 //
3 // String.prototype.startsWith with a short (≤32 characters) constant string is
4 // optimised during lowering.
5
6 function* characters(...ranges) {
7 for (let [start, end] of ranges) {
8 for (let i = start; i <= end; ++i) {
9 yield i;
10 }
11 }
12 }
13
14 const ascii = [...characters(
15 [0x41, 0x5A], // A..Z
16 [0x61, 0x7A], // a..z
17 [0x30, 0x39], // 0..9
18 )];
19
20 const latin1 = [...characters(
21 [0xC0, 0xFF], // À..ÿ
22 )];
23
24 const twoByte = [...characters(
25 [0x100, 0x17E], // Ā..ž
26 )];
27
28 function toRope(s) {
29 try {
30 return newRope(s[0], s.substring(1));
31 } catch {}
32 // newRope can fail when |s| fits into an inline string. In that case simply
33 // return the input.
34 return s;
35 }
36
37 function atomize(s) {
38 return Object.keys({[s]: 0})[0];
39 }
40
41 for (let i = 1; i <= 32; ++i) {
42 let strings = [ascii, latin1, twoByte].flatMap(codePoints => [
43 // Same string as the input.
44 String.fromCodePoint(...codePoints.slice(0, i)),
45
46 // Same length as the input, but a different string.
47 String.fromCodePoint(...codePoints.slice(1, i + 1)),
48
49 // Shorter string than the input.
50 String.fromCodePoint(...codePoints.slice(0, i - 1)),
51
52 // Longer string than the input.
53 String.fromCodePoint(...codePoints.slice(0, i + 1)),
54 ]).flatMap(x => [
55 x,
56 toRope(x),
57 newString(x, {twoByte: true}),
58 atomize(x),
59 ]);
60
61 for (let codePoints of [ascii, latin1, twoByte]) {
62 let str = String.fromCodePoint(...codePoints.slice(0, i));
63
64 let fn = Function("strings", `
65 const expected = strings.map(x => {
66 // Prevent Warp compilation when computing the expected results.
67 with ({}) ;
68 return x.startsWith("${str}");
69 });
70
71 for (let i = 0; i < 250; ++i) {
72 let idx = i % strings.length;
73 let str = strings[idx];
74
75 let actual = str.startsWith("${str}");
76 if (actual !== expected[idx]) throw new Error();
77 }
78 `);
79 fn(strings);
80 }
81 }