summaryrefslogtreecommitdiff
path: root/installed-tests/js/testEncoding.js
blob: 55d65581e89d8cb16dbfadc50019c8bc6e5251be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
// SPDX-FileCopyrightText: 2021 Evan Welsh <contact@evanwelsh.com>

// Some test inputs are derived from https://github.com/denoland/deno/blob/923214c53725651792f6d55c5401bf6b475622ea/op_crates/web/08_text_encoding.js
// Data originally from https://encoding.spec.whatwg.org/encodings.json

import Gio from 'gi://Gio';

import {arrayLikeWithExactContents} from './matchers.js';

/**
 * Loads a JSON file from a URI and parses it.
 *
 * @param {string} src the URI to load from
 * @returns {any}
 */
function loadJSONFromResource(src) {
    const file = Gio.File.new_for_uri(src);
    const [, bytes] = file.load_contents(null);

    const decoder = new TextDecoder();
    const jsonRaw = decoder.decode(bytes);
    const json = JSON.parse(jsonRaw);

    return json;
}

/**
 * Encoded form of '𝓽𝓮𝔁𝓽'
 *
 * @returns {number[]}
 */
function encodedMultibyteCharArray() {
    return [
        0xf0, 0x9d, 0x93, 0xbd, 0xf0, 0x9d, 0x93, 0xae, 0xf0, 0x9d, 0x94, 0x81,
        0xf0, 0x9d, 0x93, 0xbd,
    ];
}

describe('Text Encoding', function () {
    it('toString() uses spec-compliant tags', function () {
        const encoder = new TextEncoder();

        expect(encoder.toString()).toBe('[object TextEncoder]');

        const decoder = new TextDecoder();
        expect(decoder.toString()).toBe('[object TextDecoder]');
    });

    describe('TextEncoder', function () {
        describe('encode()', function () {
            it('can encode UTF8 (multi-byte chars)', function () {
                const input = '𝓽𝓮𝔁𝓽';
                const encoder = new TextEncoder();
                const encoded = encoder.encode(input);

                expect(encoded).toEqual(
                    arrayLikeWithExactContents([...encodedMultibyteCharArray()])
                );
            });
        });

        describe('encodeInto()', function () {
            it('can encode UTF8 (Latin chars) into a Uint8Array', function () {
                const input = 'text';
                const encoder = new TextEncoder();
                const bytes = new Uint8Array(5);
                const result = encoder.encodeInto(input, bytes);
                expect(result.read).toBe(4);
                expect(result.written).toBe(4);

                expect(bytes).toEqual(
                    arrayLikeWithExactContents([0x74, 0x65, 0x78, 0x74, 0x00])
                );
            });

            it('can fully encode UTF8 (multi-byte chars) into a Uint8Array', function () {
                const input = '𝓽𝓮𝔁𝓽';
                const encoder = new TextEncoder();
                const bytes = new Uint8Array(17);
                const result = encoder.encodeInto(input, bytes);
                expect(result.read).toBe(8);
                expect(result.written).toBe(16);

                expect(bytes).toEqual(
                    arrayLikeWithExactContents([
                        ...encodedMultibyteCharArray(),
                        0x00,
                    ])
                );
            });

            it('can partially encode UTF8 into an under-allocated Uint8Array', function () {
                const input = '𝓽𝓮𝔁𝓽';
                const encoder = new TextEncoder();
                const bytes = new Uint8Array(5);
                const result = encoder.encodeInto(input, bytes);
                expect(result.read).toBe(2);
                expect(result.written).toBe(4);

                expect(bytes).toEqual(
                    arrayLikeWithExactContents([
                        ...encodedMultibyteCharArray().slice(0, 4),
                        0x00,
                    ])
                );
            });
        });
    });

    describe('TextDecoder', function () {
        describe('decode()', function () {
            it('fatal is false by default', function () {
                const decoder = new TextDecoder();

                expect(decoder.fatal).toBeFalse();
            });

            it('ignoreBOM is false by default', function () {
                const decoder = new TextDecoder();

                expect(decoder.ignoreBOM).toBeFalse();
            });

            it('fatal is true when passed', function () {
                const decoder = new TextDecoder(undefined, {fatal: true});

                expect(decoder.fatal).toBeTrue();
            });

            it('ignoreBOM is true when passed', function () {
                const decoder = new TextDecoder(undefined, {ignoreBOM: true});

                expect(decoder.ignoreBOM).toBeTrue();
            });

            it('fatal is coerced to a boolean value', function () {
                const decoder = new TextDecoder(undefined, {fatal: 1});

                expect(decoder.fatal).toBeTrue();
            });

            it('ignoreBOM is coerced to a boolean value', function () {
                const decoder = new TextDecoder(undefined, {ignoreBOM: ''});

                expect(decoder.ignoreBOM).toBeFalse();
            });

            it('throws on empty input', function () {
                const decoder = new TextDecoder();
                const input = '';

                expect(() => decoder.decode(input)).toThrowError(
                    'Provided input cannot be converted to ArrayBufferView or ArrayBuffer'
                );
            });

            it('throws on null input', function () {
                const decoder = new TextDecoder();
                const input = null;

                expect(() => decoder.decode(input)).toThrowError(
                    'Provided input cannot be converted to ArrayBufferView or ArrayBuffer'
                );
            });

            it('throws on invalid encoding label', function () {
                expect(() => new TextDecoder('bad')).toThrowError(
                    "Invalid encoding label: 'bad'"
                );
            });

            it('decodes undefined as an empty string', function () {
                const decoder = new TextDecoder();
                const input = undefined;

                expect(decoder.decode(input)).toBe('');
            });

            it('decodes UTF-8 byte array (Uint8Array)', function () {
                const decoder = new TextDecoder();
                const input = new Uint8Array([...encodedMultibyteCharArray()]);

                expect(decoder.decode(input)).toBe('𝓽𝓮𝔁𝓽');
            });

            it('ignores byte order marker (BOM)', function () {
                const decoder = new TextDecoder('utf-8', {ignoreBOM: true});
                const input = new Uint8Array([
                    0xef,
                    0xbb,
                    0xbf,
                    ...encodedMultibyteCharArray(),
                ]);

                expect(decoder.decode(input)).toBe('𝓽𝓮𝔁𝓽');
            });

            it('handles invalid byte order marker (BOM)', function () {
                const decoder = new TextDecoder('utf-8', {ignoreBOM: true});
                const input = new Uint8Array([
                    0xef,
                    0xbb,
                    0x89,
                    ...encodedMultibyteCharArray(),
                ]);

                expect(decoder.decode(input)).toBe('ﻉ𝓽𝓮𝔁𝓽');
            });
        });

        describe('UTF-8 Encoding Converter', function () {
            it('can decode (not fatal)', function () {
                const decoder = new TextDecoder();

                const decoded = decoder.decode(new Uint8Array([120, 193, 120]));
                expect(decoded).toEqual('x�x');
            });

            it('can decode (fatal)', function () {
                const decoder = new TextDecoder(undefined, {
                    fatal: true,
                });

                expect(() => {
                    decoder.decode(new Uint8Array([120, 193, 120]));
                }).toThrowError(
                    TypeError,
                    /malformed UTF-8 character sequence/
                );
            });
        });

        describe('Multi-byte Encoding Converter (iconv)', function () {
            it('can decode Big-5', function () {
                const decoder = new TextDecoder('big5');
                const bytes = [
                    164, 164, 177, 192, 183, 124, 177, 181, 168, 252, 184, 103,
                    192, 217, 179, 161, 188, 208, 183, 199, 192, 203, 197, 231,
                    167, 189, 169, 101, 176, 85,
                ];

                const decoded = decoder.decode(new Uint8Array(bytes));
                expect(decoded).toEqual('中推會接受經濟部標準檢驗局委託');
            });

            it('can decode Big-5 with incorrect input bytes', function () {
                const decoder = new TextDecoder('big5');
                const bytes = [
                    164, 164, 177, 192, 183, 124,
                    // Invalid byte...
                    0xa1,
                ];

                const decoded = decoder.decode(new Uint8Array(bytes));
                expect(decoded).toEqual('中推會�');
            });

            it('can decode Big-5 with long incorrect input bytes', function () {
                const decoder = new TextDecoder('big5');
                const bytes = [164, 164, 177, 192, 183, 124];
                const baseLength = 1000;
                const longBytes = new Array(baseLength)
                    .fill(bytes, 0, baseLength)
                    .flat();

                // Append invalid byte sequence...
                longBytes.push(0xa3);

                const decoded = decoder.decode(new Uint8Array(longBytes));

                const baseResult = '中推會';
                const longResult = [
                    ...new Array(baseLength).fill(baseResult, 0, baseLength),
                    '�',
                ].join('');

                expect(decoded).toEqual(longResult);
            });

            it('can decode Big-5 HKSCS with supplemental characters', function () {
                // The characters below roughly mean 'hard' or 'solid' and
                // 'rooster' respectively. They were chosen for their Unicode
                // and HKSCS positioning, not meaning.

                // Big5-HKSCS bytes for the supplemental character 𠕇
                const supplementalBytes = [250, 64];
                // Big5-HKSCS bytes for the non-supplemental characters 公雞
                const nonSupplementalBytes = [164, 189, 194, 251];

                const decoder = new TextDecoder('big5-hkscs');

                // We currently allocate 12 additional bytes of padding
                // and a minimum of 256...

                // This should produce 400 non-supplemental bytes (50 * 2 * 4)
                // and 16 supplemental bytes (4 * 4)
                const repeatedNonSupplementalBytes = new Array(50).fill(nonSupplementalBytes).flat();
                const bytes = [
                    ...repeatedNonSupplementalBytes,
                    ...supplementalBytes,
                    ...repeatedNonSupplementalBytes,
                    ...supplementalBytes,
                    ...repeatedNonSupplementalBytes,
                    ...supplementalBytes,
                    ...repeatedNonSupplementalBytes,
                    ...supplementalBytes,
                ];

                const expectedNonSupplemental  = new Array(50).fill('公雞');
                const expected = [
                    ...expectedNonSupplemental,
                    '𠕇',
                    ...expectedNonSupplemental,
                    '𠕇',
                    ...expectedNonSupplemental,
                    '𠕇',
                    ...expectedNonSupplemental,
                    '𠕇',
                ].join('');

                // Calculate the number of bytes the UTF-16 characters should
                // occupy.
                const expectedU16Bytes = [...expected].reduce((prev, next) => {
                    const utf16code = next.codePointAt(0);

                    // Test whether this unit is supplemental
                    const additionalBytes = utf16code > 0xFFFF ? 2 : 0;

                    return prev + 2 + additionalBytes;
                }, 0);


                // We set a minimum buffer allocation of 256 bytes,
                // this ensures that this test exceeds that.
                expect(expectedU16Bytes / 2).toBeGreaterThan(256);

                // The length of the input bytes should always be less
                // than the expected output because UTF-16 uses 4 bytes
                // to represent some characters HKSCS needs only 2 for.
                expect(bytes.length).toBeLessThan(expectedU16Bytes);
                // 4 supplemental characters, each with two additional bytes.
                expect(bytes.length + 4 * 2).toBe(expectedU16Bytes);

                const decoded = decoder.decode(new Uint8Array(bytes));

                expect(decoded).toBe(expected);
            });
        });

        describe('Single Byte Encoding Converter', function () {
            it('can decode legacy single byte encoding (not fatal)', function () {
                const decoder = new TextDecoder('iso-8859-6');

                const decoded = decoder.decode(new Uint8Array([161, 200, 200]));
                expect(decoded).toEqual('�بب');
            });

            it('can decode legacy single byte encoding (fatal)', function () {
                const decoder = new TextDecoder('iso-8859-6', {
                    fatal: true,
                });

                expect(() => {
                    decoder.decode(new Uint8Array([161, 200, 200]));
                }).toThrowError(
                    TypeError,
                    'Invalid byte sequence in conversion input'
                );
            });

            it('can decode ASCII', function () {
                const input = new Uint8Array([0x89, 0x95, 0x9f, 0xbf]);
                const decoder = new TextDecoder('ascii');
                expect(decoder.decode(input)).toBe('‰•Ÿ¿');
            });

            // Straight from https://encoding.spec.whatwg.org/encodings.json
            const encodingsTable = loadJSONFromResource(
                'resource:///org/gjs/jsunit/modules/encodings.json'
            );

            const singleByteEncodings = encodingsTable.filter(group => {
                return group.heading === 'Legacy single-byte encodings';
            })[0].encodings;

            const buffer = new ArrayBuffer(255);
            const view = new Uint8Array(buffer);

            for (let i = 0, l = view.byteLength; i < l; i++)
                view[i] = i;

            for (let i = 0, l = singleByteEncodings.length; i < l; i++) {
                const encoding = singleByteEncodings[i];

                it(`${encoding.name} can be decoded.`, function () {
                    for (const label of encoding.labels) {
                        const decoder = new TextDecoder(label);
                        expect(() => decoder.decode(view)).not.toThrow();
                        expect(decoder.encoding).toBe(
                            encoding.name.toLowerCase()
                        );
                    }
                });
            }
        });
    });
});