Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koichik/917865 to your computer and use it in GitHub Desktop.
Save koichik/917865 to your computer and use it in GitHub Desktop.
Fix Buffer.write() with UCS-2 should not be write partial char
From 4f486eecf8a20e52455a227e2e3502f1aeb14983 Mon Sep 17 00:00:00 2001
From: koichik <koichik@improvement.jp>
Date: Thu, 14 Apr 2011 01:17:18 +0900
Subject: [PATCH] Fix Buffer.write() with UCS-2 should not be write partial char
---
src/node_buffer.cc | 6 +++++-
test/simple/test-buffer.js | 9 +++++++++
2 files changed, 14 insertions(+), 1 deletions(-)
diff --git a/src/node_buffer.cc b/src/node_buffer.cc
index b46abe1..75bac2a 100644
--- a/src/node_buffer.cc
+++ b/src/node_buffer.cc
@@ -495,7 +495,7 @@ Handle<Value> Buffer::Ucs2Write(const Arguments &args) {
size_t max_length = args[2]->IsUndefined() ? buffer->length_ - offset
: args[2]->Uint32Value();
- max_length = MIN(buffer->length_ - offset, max_length);
+ max_length = MIN(buffer->length_ - offset, max_length) / 2;
uint16_t* p = (uint16_t*)(buffer->data_ + offset);
@@ -503,6 +503,10 @@ Handle<Value> Buffer::Ucs2Write(const Arguments &args) {
0,
max_length,
String::HINT_MANY_WRITES_EXPECTED);
+
+ constructor_template->GetFunction()->Set(chars_written_sym,
+ Integer::New(written));
+
return scope.Close(Integer::New(written * 2));
}
diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js
index ac822b2..0edb642 100644
--- a/test/simple/test-buffer.js
+++ b/test/simple/test-buffer.js
@@ -256,6 +256,15 @@ console.error('f.length: %d (should be 12)', f.length);
assert.deepEqual(f, new Buffer([63, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66, 4]));
assert.equal(f.toString('ucs2'), 'привет');
+var f = new Buffer([0, 0, 0, 0, 0]);
+assert.equal(f.length, 5);
+var size = f.write('あいうえお', 'ucs2');
+console.error('bytes written to buffer: %d (should be 4)', size);
+console.error('chars written to buffer: %d (should be 2)', Buffer._charsWritten);
+assert.equal(size, 4);
+assert.equal(Buffer._charsWritten, 2);
+assert.deepEqual(f, new Buffer([0x42, 0x30, 0x44, 0x30, 0x00]));
+
var arrayIsh = {0: 0, 1: 1, 2: 2, 3: 3, length: 4};
var g = new Buffer(arrayIsh);
--
1.7.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment