// Copyright Joyent, Inc. and other Node contributors.1//2// Permission is hereby granted, free of charge, to any person obtaining a3// copy of this software and associated documentation files (the4// "Software"), to deal in the Software without restriction, including5// without limitation the rights to use, copy, modify, merge, publish,6// distribute, sublicense, and/or sell copies of the Software, and to permit7// persons to whom the Software is furnished to do so, subject to the8// following conditions:9//10// The above copyright notice and this permission notice shall be included11// in all copies or substantial portions of the Software.12//13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF15// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN16// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,17// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR18// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE19// USE OR OTHER DEALINGS IN THE SOFTWARE.2021var Buffer = require('buffer').Buffer;2223var isBufferEncoding = Buffer.isEncoding24|| function(encoding) {25switch (encoding && encoding.toLowerCase()) {26case '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;27default: return false;28}29}303132function assertEncoding(encoding) {33if (encoding && !isBufferEncoding(encoding)) {34throw new Error('Unknown encoding: ' + encoding);35}36}3738// StringDecoder provides an interface for efficiently splitting a series of39// buffers into a series of JS strings without breaking apart multi-byte40// characters. CESU-8 is handled as part of the UTF-8 encoding.41//42// @TODO Handling all encodings inside a single object makes it very difficult43// to reason about this code, so it should be split up in the future.44// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code45// points as used by CESU-8.46var StringDecoder = exports.StringDecoder = function(encoding) {47this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');48assertEncoding(encoding);49switch (this.encoding) {50case 'utf8':51// CESU-8 represents each of Surrogate Pair by 3-bytes52this.surrogateSize = 3;53break;54case 'ucs2':55case 'utf16le':56// UTF-16 represents each of Surrogate Pair by 2-bytes57this.surrogateSize = 2;58this.detectIncompleteChar = utf16DetectIncompleteChar;59break;60case 'base64':61// Base-64 stores 3 bytes in 4 chars, and pads the remainder.62this.surrogateSize = 3;63this.detectIncompleteChar = base64DetectIncompleteChar;64break;65default:66this.write = passThroughWrite;67return;68}6970// Enough space to store all bytes of a single character. UTF-8 needs 471// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).72this.charBuffer = new Buffer(6);73// Number of bytes received for the current incomplete multi-byte character.74this.charReceived = 0;75// Number of bytes expected for the current incomplete multi-byte character.76this.charLength = 0;77};787980// write decodes the given buffer and returns it as JS string that is81// guaranteed to not contain any partial multi-byte characters. Any partial82// character found at the end of the buffer is buffered up, and will be83// returned when calling write again with the remaining bytes.84//85// Note: Converting a Buffer containing an orphan surrogate to a String86// currently works, but converting a String to a Buffer (via `new Buffer`, or87// Buffer#write) will replace incomplete surrogates with the unicode88// replacement character. See https://codereview.chromium.org/121173009/ .89StringDecoder.prototype.write = function(buffer) {90var charStr = '';91// if our last write ended with an incomplete multibyte character92while (this.charLength) {93// determine how many remaining bytes this buffer has to offer for this char94var available = (buffer.length >= this.charLength - this.charReceived) ?95this.charLength - this.charReceived :96buffer.length;9798// add the new bytes to the char buffer99buffer.copy(this.charBuffer, this.charReceived, 0, available);100this.charReceived += available;101102if (this.charReceived < this.charLength) {103// still not enough chars in this buffer? wait for more ...104return '';105}106107// remove bytes belonging to the current character from the buffer108buffer = buffer.slice(available, buffer.length);109110// get the character that was split111charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);112113// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character114var charCode = charStr.charCodeAt(charStr.length - 1);115if (charCode >= 0xD800 && charCode <= 0xDBFF) {116this.charLength += this.surrogateSize;117charStr = '';118continue;119}120this.charReceived = this.charLength = 0;121122// if there are no more bytes in this buffer, just emit our char123if (buffer.length === 0) {124return charStr;125}126break;127}128129// determine and set charLength / charReceived130this.detectIncompleteChar(buffer);131132var end = buffer.length;133if (this.charLength) {134// buffer the incomplete character bytes we got135buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);136end -= this.charReceived;137}138139charStr += buffer.toString(this.encoding, 0, end);140141var end = charStr.length - 1;142var charCode = charStr.charCodeAt(end);143// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character144if (charCode >= 0xD800 && charCode <= 0xDBFF) {145var size = this.surrogateSize;146this.charLength += size;147this.charReceived += size;148this.charBuffer.copy(this.charBuffer, size, 0, size);149buffer.copy(this.charBuffer, 0, 0, size);150return charStr.substring(0, end);151}152153// or just emit the charStr154return charStr;155};156157// detectIncompleteChar determines if there is an incomplete UTF-8 character at158// the end of the given buffer. If so, it sets this.charLength to the byte159// length that character, and sets this.charReceived to the number of bytes160// that are available for this character.161StringDecoder.prototype.detectIncompleteChar = function(buffer) {162// determine how many bytes we have to check at the end of this buffer163var i = (buffer.length >= 3) ? 3 : buffer.length;164165// Figure out if one of the last i bytes of our buffer announces an166// incomplete char.167for (; i > 0; i--) {168var c = buffer[buffer.length - i];169170// See http://en.wikipedia.org/wiki/UTF-8#Description171172// 110XXXXX173if (i == 1 && c >> 5 == 0x06) {174this.charLength = 2;175break;176}177178// 1110XXXX179if (i <= 2 && c >> 4 == 0x0E) {180this.charLength = 3;181break;182}183184// 11110XXX185if (i <= 3 && c >> 3 == 0x1E) {186this.charLength = 4;187break;188}189}190this.charReceived = i;191};192193StringDecoder.prototype.end = function(buffer) {194var res = '';195if (buffer && buffer.length)196res = this.write(buffer);197198if (this.charReceived) {199var cr = this.charReceived;200var buf = this.charBuffer;201var enc = this.encoding;202res += buf.slice(0, cr).toString(enc);203}204205return res;206};207208function passThroughWrite(buffer) {209return buffer.toString(this.encoding);210}211212function utf16DetectIncompleteChar(buffer) {213this.charReceived = buffer.length % 2;214this.charLength = this.charReceived ? 2 : 0;215}216217function base64DetectIncompleteChar(buffer) {218this.charReceived = buffer.length % 3;219this.charLength = this.charReceived ? 3 : 0;220}221222223