1'use strict';
2
3const { mustNotMutateObjectDeep } = require('../common');
4const fixtures = require('../common/fixtures');
5const fs = require('fs');
6const assert = require('assert');
7const filepath = fixtures.path('x.txt');
8
9const expected = Buffer.from('xyz\n');
10
11function runTest(defaultBuffer, options) {
12  let fd;
13  try {
14    fd = fs.openSync(filepath, 'r');
15    const result = fs.readSync(fd, defaultBuffer, options);
16    assert.strictEqual(result, expected.length);
17    assert.deepStrictEqual(defaultBuffer, expected);
18  } finally {
19    if (fd != null) fs.closeSync(fd);
20  }
21}
22
23for (const options of [
24
25  // Test options object
26  { offset: 0 },
27  { length: expected.length },
28  { position: 0 },
29  { offset: 0, length: expected.length },
30  { offset: 0, position: 0 },
31  { length: expected.length, position: 0 },
32  { offset: 0, length: expected.length, position: 0 },
33
34  { offset: null },
35  { position: null },
36  { position: -1 },
37  { position: 0n },
38
39  // Test default params
40  {},
41  null,
42  undefined,
43
44  // Test if bad params are interpreted as default (not mandatory)
45  false,
46  true,
47  Infinity,
48  42n,
49  Symbol(),
50
51  // Test even more malicious corner cases
52  '4'.repeat(expected.length),
53  new String('4444'),
54  [4, 4, 4, 4],
55]) {
56  runTest(Buffer.allocUnsafe(expected.length), mustNotMutateObjectDeep(options));
57}
58