11cb0ef41Sopenharmony_ci'use strict'; 21cb0ef41Sopenharmony_cirequire('../common'); 31cb0ef41Sopenharmony_ciconst { StringDecoder } = require('string_decoder'); 41cb0ef41Sopenharmony_ciconst util = require('util'); 51cb0ef41Sopenharmony_ciconst assert = require('assert'); 61cb0ef41Sopenharmony_ci 71cb0ef41Sopenharmony_ci// Tests that, for random sequences of bytes, our StringDecoder gives the 81cb0ef41Sopenharmony_ci// same result as a direction conversion using Buffer.toString(). 91cb0ef41Sopenharmony_ci// In particular, it checks that StringDecoder aligns with V8’s own output. 101cb0ef41Sopenharmony_ci 111cb0ef41Sopenharmony_cifunction rand(max) { 121cb0ef41Sopenharmony_ci return Math.floor(Math.random() * max); 131cb0ef41Sopenharmony_ci} 141cb0ef41Sopenharmony_ci 151cb0ef41Sopenharmony_cifunction randBuf(maxLen) { 161cb0ef41Sopenharmony_ci const buf = Buffer.allocUnsafe(rand(maxLen)); 171cb0ef41Sopenharmony_ci for (let i = 0; i < buf.length; i++) 181cb0ef41Sopenharmony_ci buf[i] = rand(256); 191cb0ef41Sopenharmony_ci return buf; 201cb0ef41Sopenharmony_ci} 211cb0ef41Sopenharmony_ci 221cb0ef41Sopenharmony_ciconst encodings = [ 231cb0ef41Sopenharmony_ci 'utf16le', 'utf8', 'ascii', 'hex', 'base64', 'latin1', 'base64url', 241cb0ef41Sopenharmony_ci]; 251cb0ef41Sopenharmony_ci 261cb0ef41Sopenharmony_cifunction runSingleFuzzTest() { 271cb0ef41Sopenharmony_ci const enc = encodings[rand(encodings.length)]; 281cb0ef41Sopenharmony_ci const sd = new StringDecoder(enc); 291cb0ef41Sopenharmony_ci const bufs = []; 301cb0ef41Sopenharmony_ci const strings = []; 311cb0ef41Sopenharmony_ci 321cb0ef41Sopenharmony_ci const N = rand(10); 331cb0ef41Sopenharmony_ci for (let i = 0; i < N; ++i) { 341cb0ef41Sopenharmony_ci const buf = randBuf(50); 351cb0ef41Sopenharmony_ci bufs.push(buf); 361cb0ef41Sopenharmony_ci strings.push(sd.write(buf)); 371cb0ef41Sopenharmony_ci } 381cb0ef41Sopenharmony_ci strings.push(sd.end()); 391cb0ef41Sopenharmony_ci 401cb0ef41Sopenharmony_ci assert.strictEqual(strings.join(''), Buffer.concat(bufs).toString(enc), 411cb0ef41Sopenharmony_ci `Mismatch:\n${util.inspect(strings)}\n` + 421cb0ef41Sopenharmony_ci util.inspect(bufs.map((buf) => buf.toString('hex'))) + 431cb0ef41Sopenharmony_ci `\nfor encoding ${enc}`); 441cb0ef41Sopenharmony_ci} 451cb0ef41Sopenharmony_ci 461cb0ef41Sopenharmony_ciconst start = Date.now(); 471cb0ef41Sopenharmony_ciwhile (Date.now() - start < 100) 481cb0ef41Sopenharmony_ci runSingleFuzzTest(); 49