|
| 1 | +'use strict'; |
| 2 | +require('../common'); |
| 3 | +const { StringDecoder } = require('string_decoder'); |
| 4 | +const util = require('util'); |
| 5 | +const assert = require('assert'); |
| 6 | + |
| 7 | +// Tests that, for random sequences of bytes, our StringDecoder gives the |
| 8 | +// same result as a direction conversion using Buffer.toString(). |
| 9 | +// In particular, it checks that StringDecoder aligns with V8’s own output. |
| 10 | + |
| 11 | +function rand(max) { |
| 12 | + return Math.floor(Math.random() * max); |
| 13 | +} |
| 14 | + |
| 15 | +function randBuf(maxLen) { |
| 16 | + const buf = Buffer.allocUnsafe(rand(maxLen)); |
| 17 | + for (let i = 0; i < buf.length; i++) |
| 18 | + buf[i] = rand(256); |
| 19 | + return buf; |
| 20 | +} |
| 21 | + |
| 22 | +const encodings = [ |
| 23 | + 'utf16le', 'utf8', 'ascii', 'hex', 'base64', 'latin1' |
| 24 | +]; |
| 25 | + |
| 26 | +function runSingleFuzzTest() { |
| 27 | + const enc = encodings[rand(encodings.length)]; |
| 28 | + const sd = new StringDecoder(enc); |
| 29 | + const bufs = []; |
| 30 | + const strings = []; |
| 31 | + |
| 32 | + const N = rand(10); |
| 33 | + for (let i = 0; i < N; ++i) { |
| 34 | + const buf = randBuf(50); |
| 35 | + bufs.push(buf); |
| 36 | + strings.push(sd.write(buf)); |
| 37 | + } |
| 38 | + strings.push(sd.end()); |
| 39 | + |
| 40 | + assert.strictEqual(strings.join(''), Buffer.concat(bufs).toString(enc), |
| 41 | + `Mismatch:\n${util.inspect(strings)}\n` + |
| 42 | + util.inspect(bufs.map((buf) => buf.toString('hex'))) + |
| 43 | + `\nfor encoding ${enc}`); |
| 44 | +} |
| 45 | + |
| 46 | +const start = Date.now(); |
| 47 | +while (Date.now() - start < 100) |
| 48 | + runSingleFuzzTest(); |
0 commit comments