From d8b67230964c0fbdc13796d6bdae47eb1ca4d489 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Tue, 6 Dec 2016 02:19:57 +0100 Subject: [PATCH] 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 Reviewed-By: Ben Noordhuis Reviewed-By: Trevor Norris --- src/node_buffer.cc | 3 +++ test/parallel/test-buffer-fill.js | 23 ++++++++++------------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 540de1827f9716..0e96fd6deed8d3 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -606,6 +606,9 @@ void Fill(const FunctionCallbackInfo& args) { } else if (enc == UCS2) { node::TwoByteValue str(env->isolate(), args[1]); + if (IsBigEndian()) + SwapBytes16(reinterpret_cast(&str[0]), str_length); + memcpy(ts_obj_data + start, *str, MIN(str_length, fill_length)); } else { diff --git a/test/parallel/test-buffer-fill.js b/test/parallel/test-buffer-fill.js index 4272d686940cc7..68b8bbd69c4566 100644 --- a/test/parallel/test-buffer-fill.js +++ b/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'));