summaryrefslogtreecommitdiff
path: root/test/parallel/test-string-decoder-fuzz.js
blob: d8d018815911612bee5698f958644d963899a4c8 (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
'use strict';
require('../common');
const { StringDecoder } = require('string_decoder');
const util = require('util');
const assert = require('assert');

// Tests that, for random sequences of bytes, our StringDecoder gives the
// same result as a direction conversion using Buffer.toString().
// In particular, it checks that StringDecoder aligns with V8’s own output.

function rand(max) {
  return Math.floor(Math.random() * max);
}

function randBuf(maxLen) {
  const buf = Buffer.allocUnsafe(rand(maxLen));
  for (let i = 0; i < buf.length; i++)
    buf[i] = rand(256);
  return buf;
}

const encodings = [
  'utf16le', 'utf8', 'ascii', 'hex', 'base64', 'latin1'
];

function runSingleFuzzTest() {
  const enc = encodings[rand(encodings.length)];
  const sd = new StringDecoder(enc);
  const bufs = [];
  const strings = [];

  const N = rand(10);
  for (let i = 0; i < N; ++i) {
    const buf = randBuf(50);
    bufs.push(buf);
    strings.push(sd.write(buf));
  }
  strings.push(sd.end());

  assert.strictEqual(strings.join(''), Buffer.concat(bufs).toString(enc),
                     `Mismatch:\n${util.inspect(strings)}\n` +
                     util.inspect(bufs.map((buf) => buf.toString('hex'))) +
                     `\nfor encoding ${enc}`);
}

const start = Date.now();
while (Date.now() - start < 100)
  runSingleFuzzTest();