Skip to content
Browse files

Fix utf8 lengths

Length should always be the number of bytes in the string,
not always String.length.

If a string is passed to nsPayload, convert it to a Buffer
so we can compute the number of bytes in the string.
  • Loading branch information...
1 parent 52347d3 commit 4133ec99f607896032c767ecef380f2ad89efc3d @josh josh committed with Sep 28, 2010
Showing with 13 additions and 5 deletions.
  1. +5 −5 lib/ns.js
  2. +8 −0 test/test.js
View
10 lib/ns.js
@@ -65,6 +65,10 @@ exports.nsLength = nsLength;
var nsPayload = function(buf, off) {
off = off || 0;
+ if (typeof buf === 'string') {
+ buf = new Buffer(buf.substring(0, buf.length));
+ }
+
var len = nsPayloadLength(buf, off);
if (len < 0) {
return len;
@@ -79,11 +83,7 @@ var nsPayload = function(buf, off) {
var start = off + (nsLen - len - 1);
- if (typeof buf === 'string') {
- return buf.substring(start, start + len);
- } else if (typeof buf === 'object') {
- return buf.slice(start, start + len);
- }
+ return buf.slice(start, start + len);
};
exports.nsPayload = nsPayload;
View
8 test/test.js
@@ -94,6 +94,10 @@ var ns = require('../lib/ns');
as.equal(ns.nsPayload('3:ab'), -1);
as.equal(ns.nsPayload('3:abc'), -1);
},
+ 'utf8' : function(as) {
+ as.equal(ns.nsPayload('3:☃,'), '');
+ as.equal(ns.nsPayload(new Buffer('3:☃,')), '');
+ }
});
ts.runTests();
@@ -132,6 +136,10 @@ var ns = require('../lib/ns');
as.equal(ns.nsWrite('abc'), '3:abc,');
as.equal(ns.nsWrite('a'), '1:a,');
},
+ 'utf8' : function(as) {
+ as.equal(ns.nsWrite(''), '3:☃,');
+ as.equal(ns.nsWrite(new Buffer('')), '3:☃,');
+ },
'start' : function(as) {
as.equal(ns.nsWrite('abc', 1), '2:bc,');
as.equal(ns.nsWrite('abc', 0), '3:abc,');

0 comments on commit 4133ec9

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