Browse Source

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: https://github.com/nodejs/node/pull/9837
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
v6
Anna Henningsen 8 years ago
parent
commit
9ee915be76
No known key found for this signature in database GPG Key ID: D8B9F5AEAE84E4CF
  1. 3
      src/node_buffer.cc
  2. 23
      test/parallel/test-buffer-fill.js

3
src/node_buffer.cc

@ -606,6 +606,9 @@ void Fill(const FunctionCallbackInfo<Value>& args) {
} else if (enc == UCS2) {
node::TwoByteValue str(env->isolate(), args[1]);
if (IsBigEndian())
SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length);
memcpy(ts_obj_data + start, *str, MIN(str_length, fill_length));
} else {

23
test/parallel/test-buffer-fill.js

@ -2,13 +2,11 @@
require('../common');
const assert = require('assert');
const os = require('os');
const SIZE = 28;
const buf1 = Buffer.allocUnsafe(SIZE);
const buf2 = Buffer.allocUnsafe(SIZE);
// Default encoding
testBufs('abc');
testBufs('\u0222aa');
@ -112,8 +110,7 @@ testBufs('\u0222aa', 8, 1, 'ucs2');
testBufs('a\u0234b\u0235c\u0236', 4, -1, 'ucs2');
testBufs('a\u0234b\u0235c\u0236', 4, 1, 'ucs2');
testBufs('a\u0234b\u0235c\u0236', 12, 1, 'ucs2');
assert.strictEqual(Buffer.allocUnsafe(1).fill('\u0222', 'ucs2')[0],
os.endianness() === 'LE' ? 0x22 : 0x02);
assert.strictEqual(Buffer.allocUnsafe(1).fill('\u0222', 'ucs2')[0], 0x22);
// HEX
@ -259,15 +256,6 @@ function writeToFill(string, offset, end, encoding) {
}
} while (offset < buf2.length);
// Correction for UCS2 operations.
if (os.endianness() === 'BE' && encoding === 'ucs2') {
for (var i = 0; i < buf2.length; i += 2) {
var tmp = buf2[i];
buf2[i] = buf2[i + 1];
buf2[i + 1] = tmp;
}
}
return buf2;
}
@ -406,3 +394,12 @@ assert.throws(() => {
});
buf.fill('');
}, /^RangeError: out of range index$/);
assert.deepStrictEqual(
Buffer.allocUnsafeSlow(16).fill('ab', 'utf16le'),
Buffer.from('61006200610062006100620061006200', 'hex'));
assert.deepStrictEqual(
Buffer.allocUnsafeSlow(15).fill('ab', 'utf16le'),
Buffer.from('610062006100620061006200610062', 'hex'));

Loading…
Cancel
Save