• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22'use strict';
23const common = require('../common');
24const assert = require('assert');
25const inspect = require('util').inspect;
26const StringDecoder = require('string_decoder').StringDecoder;
27
28// Test default encoding
29let decoder = new StringDecoder();
30assert.strictEqual(decoder.encoding, 'utf8');
31
32// Should work without 'new' keyword
33const decoder2 = {};
34StringDecoder.call(decoder2);
35assert.strictEqual(decoder2.encoding, 'utf8');
36
37// UTF-8
38test('utf-8', Buffer.from('$', 'utf-8'), '$');
39test('utf-8', Buffer.from('¢', 'utf-8'), '¢');
40test('utf-8', Buffer.from('€', 'utf-8'), '€');
41test('utf-8', Buffer.from('��', 'utf-8'), '��');
42// A mixed ascii and non-ascii string
43// Test stolen from deps/v8/test/cctest/test-strings.cc
44// U+02E4 -> CB A4
45// U+0064 -> 64
46// U+12E4 -> E1 8B A4
47// U+0030 -> 30
48// U+3045 -> E3 81 85
49test(
50  'utf-8',
51  Buffer.from([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4, 0x30, 0xE3, 0x81, 0x85]),
52  '\u02e4\u0064\u12e4\u0030\u3045'
53);
54
55// Some invalid input, known to have caused trouble with chunking
56// in https://github.com/nodejs/node/pull/7310#issuecomment-226445923
57// 00: |00000000 ASCII
58// 41: |01000001 ASCII
59// B8: 10|111000 continuation
60// CC: 110|01100 two-byte head
61// E2: 1110|0010 three-byte head
62// F0: 11110|000 four-byte head
63// F1: 11110|001'another four-byte head
64// FB: 111110|11 "five-byte head", not UTF-8
65test('utf-8', Buffer.from('C9B5A941', 'hex'), '\u0275\ufffdA');
66test('utf-8', Buffer.from('E2', 'hex'), '\ufffd');
67test('utf-8', Buffer.from('E241', 'hex'), '\ufffdA');
68test('utf-8', Buffer.from('CCCCB8', 'hex'), '\ufffd\u0338');
69test('utf-8', Buffer.from('F0B841', 'hex'), '\ufffdA');
70test('utf-8', Buffer.from('F1CCB8', 'hex'), '\ufffd\u0338');
71test('utf-8', Buffer.from('F0FB00', 'hex'), '\ufffd\ufffd\0');
72test('utf-8', Buffer.from('CCE2B8B8', 'hex'), '\ufffd\u2e38');
73test('utf-8', Buffer.from('E2B8CCB8', 'hex'), '\ufffd\u0338');
74test('utf-8', Buffer.from('E2FBCC01', 'hex'), '\ufffd\ufffd\ufffd\u0001');
75test('utf-8', Buffer.from('CCB8CDB9', 'hex'), '\u0338\u0379');
76// CESU-8 of U+1D40D
77
78// V8 has changed their invalid UTF-8 handling, see
79// https://chromium-review.googlesource.com/c/v8/v8/+/671020 for more info.
80test('utf-8', Buffer.from('EDA0B5EDB08D', 'hex'),
81     '\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd');
82
83// UCS-2
84test('ucs2', Buffer.from('ababc', 'ucs2'), 'ababc');
85
86// UTF-16LE
87test('utf16le', Buffer.from('3DD84DDC', 'hex'), '\ud83d\udc4d'); // thumbs up
88
89// Additional UTF-8 tests
90decoder = new StringDecoder('utf8');
91assert.strictEqual(decoder.write(Buffer.from('E1', 'hex')), '');
92
93// A quick test for lastChar, lastNeed & lastTotal which are undocumented.
94assert(decoder.lastChar.equals(new Uint8Array([0xe1, 0, 0, 0])));
95assert.strictEqual(decoder.lastNeed, 2);
96assert.strictEqual(decoder.lastTotal, 3);
97
98assert.strictEqual(decoder.end(), '\ufffd');
99
100// ArrayBufferView tests
101const arrayBufferViewStr = 'String for ArrayBufferView tests\n';
102const inputBuffer = Buffer.from(arrayBufferViewStr.repeat(8), 'utf8');
103for (const expectView of common.getArrayBufferViews(inputBuffer)) {
104  assert.strictEqual(
105    decoder.write(expectView),
106    inputBuffer.toString('utf8')
107  );
108  assert.strictEqual(decoder.end(), '');
109}
110
111decoder = new StringDecoder('utf8');
112assert.strictEqual(decoder.write(Buffer.from('E18B', 'hex')), '');
113assert.strictEqual(decoder.end(), '\ufffd');
114
115decoder = new StringDecoder('utf8');
116assert.strictEqual(decoder.write(Buffer.from('\ufffd')), '\ufffd');
117assert.strictEqual(decoder.end(), '');
118
119decoder = new StringDecoder('utf8');
120assert.strictEqual(decoder.write(Buffer.from('\ufffd\ufffd\ufffd')),
121                   '\ufffd\ufffd\ufffd');
122assert.strictEqual(decoder.end(), '');
123
124decoder = new StringDecoder('utf8');
125assert.strictEqual(decoder.write(Buffer.from('EFBFBDE2', 'hex')), '\ufffd');
126assert.strictEqual(decoder.end(), '\ufffd');
127
128decoder = new StringDecoder('utf8');
129assert.strictEqual(decoder.write(Buffer.from('F1', 'hex')), '');
130assert.strictEqual(decoder.write(Buffer.from('41F2', 'hex')), '\ufffdA');
131assert.strictEqual(decoder.end(), '\ufffd');
132
133// Additional utf8Text test
134decoder = new StringDecoder('utf8');
135assert.strictEqual(decoder.text(Buffer.from([0x41]), 2), '');
136
137// Additional UTF-16LE surrogate pair tests
138decoder = new StringDecoder('utf16le');
139assert.strictEqual(decoder.write(Buffer.from('3DD8', 'hex')), '');
140assert.strictEqual(decoder.write(Buffer.from('4D', 'hex')), '');
141assert.strictEqual(decoder.write(Buffer.from('DC', 'hex')), '\ud83d\udc4d');
142assert.strictEqual(decoder.end(), '');
143
144decoder = new StringDecoder('utf16le');
145assert.strictEqual(decoder.write(Buffer.from('3DD8', 'hex')), '');
146assert.strictEqual(decoder.end(), '\ud83d');
147
148decoder = new StringDecoder('utf16le');
149assert.strictEqual(decoder.write(Buffer.from('3DD8', 'hex')), '');
150assert.strictEqual(decoder.write(Buffer.from('4D', 'hex')), '');
151assert.strictEqual(decoder.end(), '\ud83d');
152
153decoder = new StringDecoder('utf16le');
154assert.strictEqual(decoder.write(Buffer.from('3DD84D', 'hex')), '\ud83d');
155assert.strictEqual(decoder.end(), '');
156
157// Regression test for https://github.com/nodejs/node/issues/22358
158// (unaligned UTF-16 access).
159decoder = new StringDecoder('utf16le');
160assert.strictEqual(decoder.write(Buffer.alloc(1)), '');
161assert.strictEqual(decoder.write(Buffer.alloc(20)), '\0'.repeat(10));
162assert.strictEqual(decoder.write(Buffer.alloc(48)), '\0'.repeat(24));
163assert.strictEqual(decoder.end(), '');
164
165// Regression tests for https://github.com/nodejs/node/issues/22626
166// (not enough replacement chars when having seen more than one byte of an
167// incomplete multibyte characters).
168decoder = new StringDecoder('utf8');
169assert.strictEqual(decoder.write(Buffer.from('f69b', 'hex')), '');
170assert.strictEqual(decoder.write(Buffer.from('d1', 'hex')), '\ufffd\ufffd');
171assert.strictEqual(decoder.end(), '\ufffd');
172assert.strictEqual(decoder.write(Buffer.from('f4', 'hex')), '');
173assert.strictEqual(decoder.write(Buffer.from('bde5', 'hex')), '\ufffd\ufffd');
174assert.strictEqual(decoder.end(), '\ufffd');
175
176assert.throws(
177  () => new StringDecoder(1),
178  {
179    code: 'ERR_UNKNOWN_ENCODING',
180    name: 'TypeError',
181    message: 'Unknown encoding: 1'
182  }
183);
184
185assert.throws(
186  () => new StringDecoder('test'),
187  {
188    code: 'ERR_UNKNOWN_ENCODING',
189    name: 'TypeError',
190    message: 'Unknown encoding: test'
191  }
192);
193
194assert.throws(
195  () => new StringDecoder('utf8').write(null),
196  {
197    code: 'ERR_INVALID_ARG_TYPE',
198    name: 'TypeError',
199    message: 'The "buf" argument must be an instance of Buffer, TypedArray,' +
200      ' or DataView. Received null'
201  }
202);
203
204if (common.enoughTestMem) {
205  assert.throws(
206    () => new StringDecoder().write(Buffer.alloc((process.arch === 'ia32' ? 0x18ffffe8 : 0x1fffffe8) + 1).fill('a')),
207    {
208      code: 'ERR_STRING_TOO_LONG',
209    }
210  );
211}
212
213assert.throws(
214  () => new StringDecoder('utf8').__proto__.write(Buffer.from('abc')), // eslint-disable-line no-proto
215  {
216    code: 'ERR_INVALID_THIS',
217  }
218);
219
220// Test verifies that StringDecoder will correctly decode the given input
221// buffer with the given encoding to the expected output. It will attempt all
222// possible ways to write() the input buffer, see writeSequences(). The
223// singleSequence allows for easy debugging of a specific sequence which is
224// useful in case of test failures.
225function test(encoding, input, expected, singleSequence) {
226  let sequences;
227  if (!singleSequence) {
228    sequences = writeSequences(input.length);
229  } else {
230    sequences = [singleSequence];
231  }
232  const hexNumberRE = /.{2}/g;
233  sequences.forEach((sequence) => {
234    const decoder = new StringDecoder(encoding);
235    let output = '';
236    sequence.forEach((write) => {
237      output += decoder.write(input.slice(write[0], write[1]));
238    });
239    output += decoder.end();
240    if (output !== expected) {
241      const message =
242        `Expected "${unicodeEscape(expected)}", ` +
243        `but got "${unicodeEscape(output)}"\n` +
244        `input: ${input.toString('hex').match(hexNumberRE)}\n` +
245        `Write sequence: ${JSON.stringify(sequence)}\n` +
246        `Full Decoder State: ${inspect(decoder)}`;
247      assert.fail(message);
248    }
249  });
250}
251
252// unicodeEscape prints the str contents as unicode escape codes.
253function unicodeEscape(str) {
254  let r = '';
255  for (let i = 0; i < str.length; i++) {
256    r += `\\u${str.charCodeAt(i).toString(16)}`;
257  }
258  return r;
259}
260
261// writeSequences returns an array of arrays that describes all possible ways a
262// buffer of the given length could be split up and passed to sequential write
263// calls.
264//
265// e.G. writeSequences(3) will return: [
266//   [ [ 0, 3 ] ],
267//   [ [ 0, 2 ], [ 2, 3 ] ],
268//   [ [ 0, 1 ], [ 1, 3 ] ],
269//   [ [ 0, 1 ], [ 1, 2 ], [ 2, 3 ] ]
270// ]
271function writeSequences(length, start, sequence) {
272  if (start === undefined) {
273    start = 0;
274    sequence = [];
275  } else if (start === length) {
276    return [sequence];
277  }
278  let sequences = [];
279  for (let end = length; end > start; end--) {
280    const subSequence = sequence.concat([[start, end]]);
281    const subSequences = writeSequences(length, end, subSequence, sequences);
282    sequences = sequences.concat(subSequences);
283  }
284  return sequences;
285}
286