1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
22 var Buffer = require('buffer').Buffer;
24 var isBufferEncoding = Buffer.isEncoding
25 || function(encoding) {
26 switch (encoding && encoding.toLowerCase()) {
27 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;
28 default: return false;
33 function assertEncoding(encoding) {
34 if (encoding && !isBufferEncoding(encoding)) {
35 throw new Error('Unknown encoding: ' + encoding);
39 // StringDecoder provides an interface for efficiently splitting a series of
40 // buffers into a series of JS strings without breaking apart multi-byte
41 // characters. CESU-8 is handled as part of the UTF-8 encoding.
43 // @TODO Handling all encodings inside a single object makes it very difficult
44 // to reason about this code, so it should be split up in the future.
45 // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
46 // points as used by CESU-8.
47 var StringDecoder = exports.StringDecoder = function(encoding) {
48 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
49 assertEncoding(encoding);
50 switch (this.encoding) {
52 // CESU-8 represents each of Surrogate Pair by 3-bytes
53 this.surrogateSize = 3;
57 // UTF-16 represents each of Surrogate Pair by 2-bytes
58 this.surrogateSize = 2;
59 this.detectIncompleteChar = utf16DetectIncompleteChar;
62 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
63 this.surrogateSize = 3;
64 this.detectIncompleteChar = base64DetectIncompleteChar;
67 this.write = passThroughWrite;
71 // Enough space to store all bytes of a single character. UTF-8 needs 4
72 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
73 this.charBuffer = new Buffer(6);
74 // Number of bytes received for the current incomplete multi-byte character.
75 this.charReceived = 0;
76 // Number of bytes expected for the current incomplete multi-byte character.
81 // write decodes the given buffer and returns it as JS string that is
82 // guaranteed to not contain any partial multi-byte characters. Any partial
83 // character found at the end of the buffer is buffered up, and will be
84 // returned when calling write again with the remaining bytes.
86 // Note: Converting a Buffer containing an orphan surrogate to a String
87 // currently works, but converting a String to a Buffer (via `new Buffer`, or
88 // Buffer#write) will replace incomplete surrogates with the unicode
89 // replacement character. See https://codereview.chromium.org/121173009/ .
90 StringDecoder.prototype.write = function(buffer) {
92 // if our last write ended with an incomplete multibyte character
93 while (this.charLength) {
94 // determine how many remaining bytes this buffer has to offer for this char
95 var available = (buffer.length >= this.charLength - this.charReceived) ?
96 this.charLength - this.charReceived :
99 // add the new bytes to the char buffer
100 buffer.copy(this.charBuffer, this.charReceived, 0, available);
101 this.charReceived += available;
103 if (this.charReceived < this.charLength) {
104 // still not enough chars in this buffer? wait for more ...
108 // remove bytes belonging to the current character from the buffer
109 buffer = buffer.slice(available, buffer.length);
111 // get the character that was split
112 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
114 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
115 var charCode = charStr.charCodeAt(charStr.length - 1);
116 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
117 this.charLength += this.surrogateSize;
121 this.charReceived = this.charLength = 0;
123 // if there are no more bytes in this buffer, just emit our char
124 if (buffer.length === 0) {
130 // determine and set charLength / charReceived
131 this.detectIncompleteChar(buffer);
133 var end = buffer.length;
134 if (this.charLength) {
135 // buffer the incomplete character bytes we got
136 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
137 end -= this.charReceived;
140 charStr += buffer.toString(this.encoding, 0, end);
142 var end = charStr.length - 1;
143 var charCode = charStr.charCodeAt(end);
144 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
145 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
146 var size = this.surrogateSize;
147 this.charLength += size;
148 this.charReceived += size;
149 this.charBuffer.copy(this.charBuffer, size, 0, size);
150 buffer.copy(this.charBuffer, 0, 0, size);
151 return charStr.substring(0, end);
154 // or just emit the charStr
158 // detectIncompleteChar determines if there is an incomplete UTF-8 character at
159 // the end of the given buffer. If so, it sets this.charLength to the byte
160 // length that character, and sets this.charReceived to the number of bytes
161 // that are available for this character.
162 StringDecoder.prototype.detectIncompleteChar = function(buffer) {
163 // determine how many bytes we have to check at the end of this buffer
164 var i = (buffer.length >= 3) ? 3 : buffer.length;
166 // Figure out if one of the last i bytes of our buffer announces an
169 var c = buffer[buffer.length - i];
171 // See http://en.wikipedia.org/wiki/UTF-8#Description
174 if (i == 1 && c >> 5 == 0x06) {
180 if (i <= 2 && c >> 4 == 0x0E) {
186 if (i <= 3 && c >> 3 == 0x1E) {
191 this.charReceived = i;
194 StringDecoder.prototype.end = function(buffer) {
196 if (buffer && buffer.length)
197 res = this.write(buffer);
199 if (this.charReceived) {
200 var cr = this.charReceived;
201 var buf = this.charBuffer;
202 var enc = this.encoding;
203 res += buf.slice(0, cr).toString(enc);
209 function passThroughWrite(buffer) {
210 return buffer.toString(this.encoding);
213 function utf16DetectIncompleteChar(buffer) {
214 this.charReceived = buffer.length % 2;
215 this.charLength = this.charReceived ? 2 : 0;
218 function base64DetectIncompleteChar(buffer) {
219 this.charReceived = buffer.length % 3;
220 this.charLength = this.charReceived ? 3 : 0;