Skip to content

Commit d8b6723

Browse files
addaleaxFishrock123
authored andcommitted
buffer: handle UCS2 .fill() properly on BE
There was a byte-order mismatch for `buffer#fill` on big-endian platforms. Weirdly, the tests seemed to expect that wrong behaviour. PR-URL: #9837 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Ben Noordhuis <[email protected]> Reviewed-By: Trevor Norris <[email protected]>
1 parent 09ec5db commit d8b6723

File tree

2 files changed

+13
-13
lines changed

2 files changed

+13
-13
lines changed

src/node_buffer.cc

+3
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,9 @@ void Fill(const FunctionCallbackInfo<Value>& args) {
606606

607607
} else if (enc == UCS2) {
608608
node::TwoByteValue str(env->isolate(), args[1]);
609+
if (IsBigEndian())
610+
SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length);
611+
609612
memcpy(ts_obj_data + start, *str, MIN(str_length, fill_length));
610613

611614
} else {

test/parallel/test-buffer-fill.js

+10-13
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,11 @@
22

33
require('../common');
44
const assert = require('assert');
5-
const os = require('os');
65
const SIZE = 28;
76

87
const buf1 = Buffer.allocUnsafe(SIZE);
98
const buf2 = Buffer.allocUnsafe(SIZE);
109

11-
1210
// Default encoding
1311
testBufs('abc');
1412
testBufs('\u0222aa');
@@ -112,8 +110,7 @@ testBufs('\u0222aa', 8, 1, 'ucs2');
112110
testBufs('a\u0234b\u0235c\u0236', 4, -1, 'ucs2');
113111
testBufs('a\u0234b\u0235c\u0236', 4, 1, 'ucs2');
114112
testBufs('a\u0234b\u0235c\u0236', 12, 1, 'ucs2');
115-
assert.strictEqual(Buffer.allocUnsafe(1).fill('\u0222', 'ucs2')[0],
116-
os.endianness() === 'LE' ? 0x22 : 0x02);
113+
assert.strictEqual(Buffer.allocUnsafe(1).fill('\u0222', 'ucs2')[0], 0x22);
117114

118115

119116
// HEX
@@ -259,15 +256,6 @@ function writeToFill(string, offset, end, encoding) {
259256
}
260257
} while (offset < buf2.length);
261258

262-
// Correction for UCS2 operations.
263-
if (os.endianness() === 'BE' && encoding === 'ucs2') {
264-
for (var i = 0; i < buf2.length; i += 2) {
265-
var tmp = buf2[i];
266-
buf2[i] = buf2[i + 1];
267-
buf2[i + 1] = tmp;
268-
}
269-
}
270-
271259
return buf2;
272260
}
273261

@@ -406,3 +394,12 @@ assert.throws(() => {
406394
});
407395
buf.fill('');
408396
}, /^RangeError: out of range index$/);
397+
398+
399+
assert.deepStrictEqual(
400+
Buffer.allocUnsafeSlow(16).fill('ab', 'utf16le'),
401+
Buffer.from('61006200610062006100620061006200', 'hex'));
402+
403+
assert.deepStrictEqual(
404+
Buffer.allocUnsafeSlow(15).fill('ab', 'utf16le'),
405+
Buffer.from('610062006100620061006200610062', 'hex'));

0 commit comments

Comments
 (0)