Skip to content

Commit

Permalink
buffer: handle UCS2 .fill() properly on BE
Browse files Browse the repository at this point in the history
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 <jasnell@gmail.com>
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
  • Loading branch information
addaleax authored and MylesBorins committed Jan 24, 2017
1 parent 2312b0b commit 60d5f6b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 13 deletions.
3 changes: 3 additions & 0 deletions src/node_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,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 {
Expand Down
23 changes: 10 additions & 13 deletions test/parallel/test-buffer-fill.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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'));

0 comments on commit 60d5f6b

Please sign in to comment.