Skip to content
Browse files

Fix Buffer drops last null character in UTF-8

Reproduce:

    $ node
    > buf = new Buffer('\0')
    <Buffer >
    > buf.length
    0
    > buf = new Buffer(1)
    <Buffer 28>
    > buf.write('\0')
    0

This patch fixes a part of #394.
  • Loading branch information...
1 parent d6ec8f6 commit e50a75115990118083ae996403be29657e34082e @koichik committed Jun 22, 2011
Showing with 16 additions and 1 deletion.
  1. +4 −1 src/node_buffer.cc
  2. +12 −0 test/simple/test-buffer.js
View
5 src/node_buffer.cc
@@ -468,7 +468,10 @@ Handle<Value> Buffer::Utf8Write(const Arguments &args) {
constructor_template->GetFunction()->Set(chars_written_sym,
Integer::New(char_written));
- if (written > 0 && p[written-1] == '\0') written--;
+ if (written > 0 && p[written-1] == '\0' &&
+ ((written < max_length) || (written > s->Utf8Length()))) {
+ written--;
+ }
return scope.Close(Integer::New(written));
}
View
12 test/simple/test-buffer.js
@@ -526,3 +526,15 @@ assert.equal(0xef, b[3]);
assert.throws(function() {
new Buffer('"pong"', 0, 6, 8031, '127.0.0.1')
});
+
+// Test null terminated UTF-8 string
+var buf = new Buffer('\0');
+assert.equal(buf.length, 1);
+buf = new Buffer('\0\0');
+assert.equal(buf.length, 2);
+buf = new Buffer(10);
+var written = buf.write('あいう'); // 3bytes * 3
+assert.equal(written, 9);
+written = buf.write('あいう\0'); // 3bytes * 3 + 1byte
+assert.equal(written, 10);
+

0 comments on commit e50a751

Please sign in to comment.
Something went wrong with that request. Please try again.