From 6df574b744f376b18a6697595717c9fd6abd59e9 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Sat, 15 Oct 2011 03:10:53 +0200 Subject: [PATCH] net: properly account multi-byte chars in .bytesWritten --- lib/net.js | 4 ++-- test/simple/test-net-connect-buffer.js | 24 +++++++++++++++++------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/lib/net.js b/lib/net.js index 8404d6f44c..cb8e25ed60 100644 --- a/lib/net.js +++ b/lib/net.js @@ -381,13 +381,13 @@ Socket.prototype.write = function(data, arg1, arg2) { } } - this.bytesWritten += data.length; - // Change strings to buffers. SLOW if (typeof data == 'string') { data = new Buffer(data, encoding); } + this.bytesWritten += data.length; + // If we are still connecting, then buffer this for later. if (this._connecting) { this._connectQueueSize += data.length; diff --git a/test/simple/test-net-connect-buffer.js b/test/simple/test-net-connect-buffer.js index 2764e5c9c6..9fbf18c839 100644 --- a/test/simple/test-net-connect-buffer.js +++ b/test/simple/test-net-connect-buffer.js @@ -24,7 +24,7 @@ var assert = require('assert'); var net = require('net'); var tcpPort = common.PORT; -var fooWritten = false; +var dataWritten = false; var connectHappened = false; var tcp = net.Server(function(s) { @@ -38,7 +38,7 @@ var tcp = net.Server(function(s) { }); s.on('end', function() { - assert.equal('foobar', buf); + assert.equal(buf, "L'État, c'est moi"); console.log('tcp socket disconnect'); s.end(); }); @@ -63,19 +63,29 @@ tcp.listen(common.PORT, function() { assert.equal('opening', socket.readyState); - var r = socket.write('foo', function() { - fooWritten = true; + // Write a string that contains a multi-byte character sequence to test that + // `bytesWritten` is incremented with the # of bytes, not # of characters. + var a = "L'État, c'est "; + var b = "moi"; + + // We're still connecting at this point so the datagram is first pushed onto + // the connect queue. Make sure that it's not added to `bytesWritten` again + // when the actual write happens. + var r = socket.write(a, function() { + dataWritten = true; assert.ok(connectHappened); - console.error('foo written'); + assert.equal(socket.bytesWritten, Buffer(a + b).length); + console.error('data written'); }); + assert.equal(socket.bytesWritten, Buffer(a).length); assert.equal(false, r); - socket.end('bar'); + socket.end(b); assert.equal('opening', socket.readyState); }); process.on('exit', function() { assert.ok(connectHappened); - assert.ok(fooWritten); + assert.ok(dataWritten); });