• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3const common = require('../common');
4
5if (!common.hasIntl)
6  common.skip('missing Intl');
7
8const buffer = require('buffer');
9const assert = require('assert');
10const orig = Buffer.from('těst ☕', 'utf8');
11
12// Test Transcoding
13const tests = {
14  'latin1': [0x74, 0x3f, 0x73, 0x74, 0x20, 0x3f],
15  'ascii': [0x74, 0x3f, 0x73, 0x74, 0x20, 0x3f],
16  'ucs2': [0x74, 0x00, 0x1b, 0x01, 0x73,
17           0x00, 0x74, 0x00, 0x20, 0x00,
18           0x15, 0x26]
19};
20
21for (const test in tests) {
22  const dest = buffer.transcode(orig, 'utf8', test);
23  assert.strictEqual(dest.length, tests[test].length, `utf8->${test} length`);
24  for (let n = 0; n < tests[test].length; n++)
25    assert.strictEqual(dest[n], tests[test][n], `utf8->${test} char ${n}`);
26}
27
28{
29  const dest = buffer.transcode(Buffer.from(tests.ucs2), 'ucs2', 'utf8');
30  assert.strictEqual(dest.toString(), orig.toString());
31}
32
33{
34  const utf8 = Buffer.from('€'.repeat(4000), 'utf8');
35  const ucs2 = Buffer.from('€'.repeat(4000), 'ucs2');
36  const utf8_to_ucs2 = buffer.transcode(utf8, 'utf8', 'ucs2');
37  const ucs2_to_utf8 = buffer.transcode(ucs2, 'ucs2', 'utf8');
38  assert.deepStrictEqual(utf8, ucs2_to_utf8);
39  assert.deepStrictEqual(ucs2, utf8_to_ucs2);
40  assert.strictEqual(ucs2_to_utf8.toString('utf8'),
41                     utf8_to_ucs2.toString('ucs2'));
42}
43
44assert.throws(
45  () => buffer.transcode(null, 'utf8', 'ascii'),
46  {
47    name: 'TypeError',
48    code: 'ERR_INVALID_ARG_TYPE',
49    message: 'The "source" argument must be an instance of Buffer ' +
50             'or Uint8Array. Received null'
51  }
52);
53
54assert.throws(
55  () => buffer.transcode(Buffer.from('a'), 'b', 'utf8'),
56  /^Error: Unable to transcode Buffer \[U_ILLEGAL_ARGUMENT_ERROR\]/
57);
58
59assert.throws(
60  () => buffer.transcode(Buffer.from('a'), 'uf8', 'b'),
61  /^Error: Unable to transcode Buffer \[U_ILLEGAL_ARGUMENT_ERROR\]$/
62);
63
64assert.deepStrictEqual(
65  buffer.transcode(Buffer.from('hi', 'ascii'), 'ascii', 'utf16le'),
66  Buffer.from('hi', 'utf16le'));
67assert.deepStrictEqual(
68  buffer.transcode(Buffer.from('hi', 'latin1'), 'latin1', 'utf16le'),
69  Buffer.from('hi', 'utf16le'));
70assert.deepStrictEqual(
71  buffer.transcode(Buffer.from('hä', 'latin1'), 'latin1', 'utf16le'),
72  Buffer.from('hä', 'utf16le'));
73
74// Test that Uint8Array arguments are okay.
75{
76  const uint8array = new Uint8Array([...Buffer.from('hä', 'latin1')]);
77  assert.deepStrictEqual(
78    buffer.transcode(uint8array, 'latin1', 'utf16le'),
79    Buffer.from('hä', 'utf16le'));
80}
81
82{
83  const dest = buffer.transcode(new Uint8Array(), 'utf8', 'latin1');
84  assert.strictEqual(dest.length, 0);
85}
86
87// Test that it doesn't crash
88{
89  buffer.transcode(new buffer.SlowBuffer(1), 'utf16le', 'ucs2');
90}
91