1'use strict';
2
3const common = require('../../common');
4const skipMessage = 'intensive toString tests due to memory confinements';
5if (!common.enoughTestMem)
6  common.skip(skipMessage);
7
8const binding = require(`./build/${common.buildType}/binding`);
9const assert = require('assert');
10
11// v8 fails silently if string length > v8::String::kMaxLength
12// v8::String::kMaxLength defined in v8.h
13const kStringMaxLength = require('buffer').constants.MAX_STRING_LENGTH;
14
15let buf;
16try {
17  buf = Buffer.allocUnsafe(kStringMaxLength + 1);
18} catch (e) {
19  // If the exception is not due to memory confinement then rethrow it.
20  if (e.message !== 'Array buffer allocation failed') throw (e);
21  common.skip(skipMessage);
22}
23
24// Ensure we have enough memory available for future allocations to succeed.
25if (!binding.ensureAllocation(2 * kStringMaxLength))
26  common.skip(skipMessage);
27
28const stringLengthHex = kStringMaxLength.toString(16);
29
30assert.throws(() => {
31  buf.toString();
32}, (e) => {
33  if (e.message !== 'Array buffer allocation failed') {
34    common.expectsError({
35      message: `Cannot create a string longer than 0x${stringLengthHex} ` +
36               'characters',
37      code: 'ERR_STRING_TOO_LONG',
38      name: 'Error',
39    })(e);
40    return true;
41  }
42  return true;
43});
44
45assert.throws(() => {
46  buf.toString('utf8');
47}, {
48  message: `Cannot create a string longer than 0x${stringLengthHex} ` +
49           'characters',
50  code: 'ERR_STRING_TOO_LONG',
51  name: 'Error',
52});
53