diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..206320c --- /dev/null +++ b/.npmignore @@ -0,0 +1,2 @@ +build +test diff --git a/build/build.js b/build/build.js index 46470cf..1a6e8d5 100755 --- a/build/build.js +++ b/build/build.js @@ -9,7 +9,7 @@ const hyperquest = require('hyperzip')(require('hyperdirect')) , files = require('./files') , testReplace = require('./test-replacements') - , srcurlpfx = 'https://raw.github.com/joyent/node/v' + process.argv[2] + '-release/' + , srcurlpfx = 'https://raw.githubusercontent.com/joyent/node/v' + process.argv[2] + '-release/' , libsrcurl = srcurlpfx + 'lib/' , testsrcurl = srcurlpfx + 'test/simple/' , testlisturl = 'https://github.com/joyent/node/tree/v' + process.argv[2] + '-release/test/simple' @@ -91,4 +91,4 @@ processFile( testsrcurl + '../common.js' , path.join(testourroot, '../common.js') , testReplace['common.js'] -) \ No newline at end of file +) diff --git a/build/files.js b/build/files.js index 24d4d60..7396a4f 100644 --- a/build/files.js +++ b/build/files.js @@ -9,9 +9,26 @@ module.exports['string_decoder.js'] = [ // pull in Bufer as a require + // add Buffer.isEncoding where missing [ /^(\/\/ USE OR OTHER DEALINGS IN THE SOFTWARE\.)/m - , '$1\n\nvar Buffer = require(\'buffer\').Buffer;' + , '$1\n\nvar Buffer = require(\'buffer\').Buffer;' + + '\n' + + '\nvar isBufferEncoding = Buffer.isEncoding' + + '\n || function(encoding) {' + + '\n switch (encoding && encoding.toLowerCase()) {' + + '\n case \'hex\': case \'utf8\': case \'utf-8\': case \'ascii\': case \'binary\': case \'base64\': case \'ucs2\': case \'ucs-2\': case \'utf16le\': case \'utf-16le\': case \'raw\': return true;' + + '\n default: return false;' + + '\n }' + + '\n }' + + '\n' + + ] + + // use custom Buffer.isEncoding reference + , [ + /Buffer\.isEncoding\(/g + , 'isBufferEncoding\(' ] ] diff --git a/index.js b/index.js index 80edb05..b00e54f 100644 --- a/index.js +++ b/index.js @@ -21,12 +21,29 @@ var Buffer = require('buffer').Buffer; +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + function assertEncoding(encoding) { - if (encoding && !Buffer.isEncoding(encoding)) { + if (encoding && !isBufferEncoding(encoding)) { throw new Error('Unknown encoding: ' + encoding); } } +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. var StringDecoder = exports.StringDecoder = function(encoding) { this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); assertEncoding(encoding); @@ -51,37 +68,50 @@ var StringDecoder = exports.StringDecoder = function(encoding) { return; } + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. this.charLength = 0; }; +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . StringDecoder.prototype.write = function(buffer) { var charStr = ''; - var offset = 0; - // if our last write ended with an incomplete multibyte character while (this.charLength) { // determine how many remaining bytes this buffer has to offer for this char - var i = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, offset, i); - this.charReceived += (i - offset); - offset = i; + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; if (this.charReceived < this.charLength) { // still not enough chars in this buffer? wait for more ... return ''; } + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + // get the character that was split charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - // lead surrogate (D800-DBFF) is also the incomplete character + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character var charCode = charStr.charCodeAt(charStr.length - 1); if (charCode >= 0xD800 && charCode <= 0xDBFF) { this.charLength += this.surrogateSize; @@ -91,34 +121,33 @@ StringDecoder.prototype.write = function(buffer) { this.charReceived = this.charLength = 0; // if there are no more bytes in this buffer, just emit our char - if (i == buffer.length) return charStr; - - // otherwise cut off the characters end from the beginning of this buffer - buffer = buffer.slice(i, buffer.length); + if (buffer.length === 0) { + return charStr; + } break; } - var lenIncomplete = this.detectIncompleteChar(buffer); + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); var end = buffer.length; if (this.charLength) { // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - lenIncomplete, end); - this.charReceived = lenIncomplete; - end -= lenIncomplete; + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; } charStr += buffer.toString(this.encoding, 0, end); var end = charStr.length - 1; var charCode = charStr.charCodeAt(end); - // lead surrogate (D800-DBFF) is also the incomplete character + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character if (charCode >= 0xD800 && charCode <= 0xDBFF) { var size = this.surrogateSize; this.charLength += size; this.charReceived += size; this.charBuffer.copy(this.charBuffer, size, 0, size); - this.charBuffer.write(charStr.charAt(charStr.length - 1), this.encoding); + buffer.copy(this.charBuffer, 0, 0, size); return charStr.substring(0, end); } @@ -126,6 +155,10 @@ StringDecoder.prototype.write = function(buffer) { return charStr; }; +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. StringDecoder.prototype.detectIncompleteChar = function(buffer) { // determine how many bytes we have to check at the end of this buffer var i = (buffer.length >= 3) ? 3 : buffer.length; @@ -155,8 +188,7 @@ StringDecoder.prototype.detectIncompleteChar = function(buffer) { break; } } - - return i; + this.charReceived = i; }; StringDecoder.prototype.end = function(buffer) { @@ -179,13 +211,11 @@ function passThroughWrite(buffer) { } function utf16DetectIncompleteChar(buffer) { - var incomplete = this.charReceived = buffer.length % 2; - this.charLength = incomplete ? 2 : 0; - return incomplete; + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; } function base64DetectIncompleteChar(buffer) { - var incomplete = this.charReceived = buffer.length % 3; - this.charLength = incomplete ? 3 : 0; - return incomplete; + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; } diff --git a/package.json b/package.json index 1efbc84..f2dd499 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "string_decoder", - "version": "0.10.24", + "version": "0.10.31", "description": "The string_decoder module from Node core", "main": "index.js", "dependencies": {}, diff --git a/test/common.js b/test/common.js index ed5ff08..e961687 100644 --- a/test/common.js +++ b/test/common.js @@ -20,6 +20,7 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. var path = require('path'); +var fs = require('fs'); var assert = require('assert'); exports.testDir = path.dirname(__filename); @@ -30,8 +31,19 @@ exports.PORT = +process.env.NODE_COMMON_PORT || 12346; if (process.platform === 'win32') { exports.PIPE = '\\\\.\\pipe\\libuv-test'; + exports.opensslCli = path.join(process.execPath, '..', 'openssl-cli.exe'); } else { exports.PIPE = exports.tmpDir + '/test.sock'; + exports.opensslCli = path.join(process.execPath, '..', 'openssl-cli'); +} +if (!fs.existsSync(exports.opensslCli)) + exports.opensslCli = false; + +if (process.platform === 'win32') { + exports.faketimeCli = false; +} else { + exports.faketimeCli = path.join(__dirname, "..", "tools", "faketime", "src", + "faketime"); } var util = require('util'); diff --git a/test/simple/test-string-decoder.js b/test/simple/test-string-decoder.js index 7f69f7e..6d6db2f 100644 --- a/test/simple/test-string-decoder.js +++ b/test/simple/test-string-decoder.js @@ -22,109 +22,14 @@ var common = require('../common'); var assert = require('assert'); var StringDecoder = require('../../').StringDecoder; -var decoder = new StringDecoder('utf8'); - - - -var buffer = new Buffer('$'); -assert.deepEqual('$', decoder.write(buffer)); - -buffer = new Buffer('¢'); -assert.deepEqual('', decoder.write(buffer.slice(0, 1))); -assert.deepEqual('¢', decoder.write(buffer.slice(1, 2))); - -buffer = new Buffer('€'); -assert.deepEqual('', decoder.write(buffer.slice(0, 1))); -assert.deepEqual('', decoder.write(buffer.slice(1, 2))); -assert.deepEqual('€', decoder.write(buffer.slice(2, 3))); - -buffer = new Buffer([0xF0, 0xA4, 0xAD, 0xA2]); -var s = ''; -s += decoder.write(buffer.slice(0, 1)); -s += decoder.write(buffer.slice(1, 2)); -s += decoder.write(buffer.slice(2, 3)); -s += decoder.write(buffer.slice(3, 4)); -assert.ok(s.length > 0); - -// CESU-8 -buffer = new Buffer('EDA0BDEDB18D', 'hex'); // THUMBS UP SIGN (in CESU-8) -var s = ''; -s += decoder.write(buffer.slice(0, 1)); -s += decoder.write(buffer.slice(1, 2)); -s += decoder.write(buffer.slice(2, 3)); // complete lead surrogate -assert.equal(s, ''); -s += decoder.write(buffer.slice(3, 4)); -s += decoder.write(buffer.slice(4, 5)); -s += decoder.write(buffer.slice(5, 6)); // complete trail surrogate -assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) - -var s = ''; -s += decoder.write(buffer.slice(0, 2)); -s += decoder.write(buffer.slice(2, 4)); // complete lead surrogate -assert.equal(s, ''); -s += decoder.write(buffer.slice(4, 6)); // complete trail surrogate -assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) - -var s = ''; -s += decoder.write(buffer.slice(0, 3)); // complete lead surrogate -assert.equal(s, ''); -s += decoder.write(buffer.slice(3, 6)); // complete trail surrogate -assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) - -var s = ''; -s += decoder.write(buffer.slice(0, 4)); // complete lead surrogate -assert.equal(s, ''); -s += decoder.write(buffer.slice(4, 5)); -s += decoder.write(buffer.slice(5, 6)); // complete trail surrogate -assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) - -var s = ''; -s += decoder.write(buffer.slice(0, 5)); // complete lead surrogate -assert.equal(s, ''); -s += decoder.write(buffer.slice(5, 6)); // complete trail surrogate -assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) - -var s = ''; -s += decoder.write(buffer.slice(0, 6)); -assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) - - -// UCS-2 -decoder = new StringDecoder('ucs2'); -buffer = new Buffer('ab', 'ucs2'); -assert.equal(decoder.write(buffer), 'ab'); // 2 complete chars -buffer = new Buffer('abc', 'ucs2'); -assert.equal(decoder.write(buffer.slice(0, 3)), 'a'); // 'a' and first of 'b' -assert.equal(decoder.write(buffer.slice(3, 6)), 'bc'); // second of 'b' and 'c' - - -// UTF-16LE -buffer = new Buffer('3DD84DDC', 'hex'); // THUMBS UP SIGN (in CESU-8) -var s = ''; -s += decoder.write(buffer.slice(0, 1)); -s += decoder.write(buffer.slice(1, 2)); // complete lead surrogate -assert.equal(s, ''); -s += decoder.write(buffer.slice(2, 3)); -s += decoder.write(buffer.slice(3, 4)); // complete trail surrogate -assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) - -var s = ''; -s += decoder.write(buffer.slice(0, 2)); // complete lead surrogate -assert.equal(s, ''); -s += decoder.write(buffer.slice(2, 4)); // complete trail surrogate -assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) - -var s = ''; -s += decoder.write(buffer.slice(0, 3)); // complete lead surrogate -assert.equal(s, ''); -s += decoder.write(buffer.slice(3, 4)); // complete trail surrogate -assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) - -var s = ''; -s += decoder.write(buffer.slice(0, 4)); -assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) +process.stdout.write('scanning '); +// UTF-8 +test('utf-8', new Buffer('$', 'utf-8'), '$'); +test('utf-8', new Buffer('¢', 'utf-8'), '¢'); +test('utf-8', new Buffer('€', 'utf-8'), '€'); +test('utf-8', new Buffer('𤭢', 'utf-8'), '𤭢'); // A mixed ascii and non-ascii string // Test stolen from deps/v8/test/cctest/test-strings.cc // U+02E4 -> CB A4 @@ -132,32 +37,86 @@ assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) // U+12E4 -> E1 8B A4 // U+0030 -> 30 // U+3045 -> E3 81 85 -var expected = '\u02e4\u0064\u12e4\u0030\u3045'; -var buffer = new Buffer([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4, - 0x30, 0xE3, 0x81, 0x85]); -var charLengths = [0, 0, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5]; +test( + 'utf-8', + new Buffer([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4, 0x30, 0xE3, 0x81, 0x85]), + '\u02e4\u0064\u12e4\u0030\u3045' +); + +// CESU-8 +test('utf-8', new Buffer('EDA0BDEDB18D', 'hex'), '\ud83d\udc4d'); // thumbs up + +// UCS-2 +test('ucs2', new Buffer('ababc', 'ucs2'), 'ababc'); + +// UTF-16LE +test('ucs2', new Buffer('3DD84DDC', 'hex'), '\ud83d\udc4d'); // thumbs up -// Split the buffer into 3 segments -// |----|------|-------| -// 0 i j buffer.length -// Scan through every possible 3 segment combination -// and make sure that the string is always parsed. -common.print('scanning '); -for (var j = 2; j < buffer.length; j++) { - for (var i = 1; i < j; i++) { - var decoder = new StringDecoder('utf8'); +console.log(' crayon!'); - var sum = decoder.write(buffer.slice(0, i)); +// test verifies that StringDecoder will correctly decode the given input +// buffer with the given encoding to the expected output. It will attempt all +// possible ways to write() the input buffer, see writeSequences(). The +// singleSequence allows for easy debugging of a specific sequence which is +// useful in case of test failures. +function test(encoding, input, expected, singleSequence) { + var sequences; + if (!singleSequence) { + sequences = writeSequences(input.length); + } else { + sequences = [singleSequence]; + } + sequences.forEach(function(sequence) { + var decoder = new StringDecoder(encoding); + var output = ''; + sequence.forEach(function(write) { + output += decoder.write(input.slice(write[0], write[1])); + }); + process.stdout.write('.'); + if (output !== expected) { + var message = + 'Expected "'+unicodeEscape(expected)+'", '+ + 'but got "'+unicodeEscape(output)+'"\n'+ + 'Write sequence: '+JSON.stringify(sequence)+'\n'+ + 'Decoder charBuffer: 0x'+decoder.charBuffer.toString('hex')+'\n'+ + 'Full Decoder State: '+JSON.stringify(decoder, null, 2); + assert.fail(output, expected, message); + } + }); +} - // just check that we've received the right amount - // after the first write - assert.equal(charLengths[i], sum.length); +// unicodeEscape prints the str contents as unicode escape codes. +function unicodeEscape(str) { + var r = ''; + for (var i = 0; i < str.length; i++) { + r += '\\u'+str.charCodeAt(i).toString(16); + } + return r; +} - sum += decoder.write(buffer.slice(i, j)); - sum += decoder.write(buffer.slice(j, buffer.length)); - assert.equal(expected, sum); - common.print('.'); +// writeSequences returns an array of arrays that describes all possible ways a +// buffer of the given length could be split up and passed to sequential write +// calls. +// +// e.G. writeSequences(3) will return: [ +// [ [ 0, 3 ] ], +// [ [ 0, 2 ], [ 2, 3 ] ], +// [ [ 0, 1 ], [ 1, 3 ] ], +// [ [ 0, 1 ], [ 1, 2 ], [ 2, 3 ] ] +// ] +function writeSequences(length, start, sequence) { + if (start === undefined) { + start = 0; + sequence = [] + } else if (start === length) { + return [sequence]; } + var sequences = []; + for (var end = length; end > start; end--) { + var subSequence = sequence.concat([[start, end]]); + var subSequences = writeSequences(length, end, subSequence, sequences); + sequences = sequences.concat(subSequences); + } + return sequences; } -console.log(' crayon!');