Skip to content

Commit

Permalink
fix: getRawString emoji
Browse files Browse the repository at this point in the history
  • Loading branch information
tangyao committed Sep 28, 2015
1 parent d2a458b commit c9410d1
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 7 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Expand Up @@ -2,5 +2,6 @@ language: node_js
node_js:
- '0.11'
- '0.10'
- '4.0.0'
script: "npm run test-travis"
after_script: "npm install coveralls@2 && cat ./coverage/lcov.info | coveralls"
19 changes: 17 additions & 2 deletions lib/byte.js
Expand Up @@ -398,8 +398,23 @@ ByteBuffer.prototype.getRawString = function (index, length) {
// getRawString() => current offset char string
index = this._offset++;
} else if (typeof length === 'number') {
// getRawString(index, length);
return this._bytes.toString('utf8', index, index + length);
var data = [];
for (var pos = index, end = index + length; pos < end; pos++) {
var ch = this._bytes[pos];
if (ch < 0x80) {
data.push(ch);
} else if ((ch & 0xe0) === 0xc0) {
var ch1 = this._bytes[++pos];
var v = ((ch & 0x1f) << 6) + (ch1 & 0x3f);
data.push(v);
} else if ((ch & 0xf0) === 0xe0) {
var ch1 = this._bytes[++pos];
var ch2 = this._bytes[++pos];
var v = ((ch & 0x0f) << 12) + ((ch1 & 0x3f) << 6) + (ch2 & 0x3f);
data.push(v);
}
}
return String.fromCharCode.apply(null, data);
}
return String.fromCharCode(this._bytes[index]);
};
Expand Down
9 changes: 4 additions & 5 deletions test/byte.test.js
Expand Up @@ -497,29 +497,28 @@ describe('byte.test.js', function () {
it('should put emoji', function () {
// utf8
var bytes = ByteBuffer.allocate(1);
var str = new Buffer('aGVsbG/ppoPlsLI=', 'base64').toString();
var str = 'hello\u9983\u5c32';
bytes.putRawString(str);
bytes.toString().should.eql('<ByteBuffer 68 65 6c 6c 6f e9 a6 83 e5 b0 b2>');
bytes.getRawString(0, 11).should.eql(str);
// gbk
var bytes = ByteBuffer.allocate(1);
var str = new Buffer('aGVsbG/wn4y8', 'base64').toString();
var str = 'hello\ud83c\udf3c';
bytes.putRawString(str);
bytes.toString().should.eql('<ByteBuffer 68 65 6c 6c 6f ed a0 bc ed bc bc>');
bytes.getRawString(0, 11).should.eql(str);

// 😀Www那
var bytes = ByteBuffer.allocate(1);
// java encode bytes: [-19, -96, -67, -19, -72, -128, 87, 119, 119, -23, -126, -93]
var str = new Buffer([-19, -96, -67, -19, -72, -128, 87, 119, 119, -23, -126, -93]).toString();
var str = '\ud83d\ude00Www那';
bytes.putRawString(str);
bytes.toString().should.eql('<ByteBuffer ed a0 bd ed b8 80 57 77 77 e9 82 a3>');
bytes.getRawString(0, 12).should.eql(str);

// Construction of a special test case which triggers the bug
// of allocating insufficient space via _checkSize
var bytes = ByteBuffer.allocate(4);
var str = new Buffer([-19, -96, -67, -19, -72, -128]).toString();
var str = '\ud83d\ude00';
bytes.putRawString(str);
bytes.toString().should.eql('<ByteBuffer ed a0 bd ed b8 80>');
});
Expand Down

0 comments on commit c9410d1

Please sign in to comment.