doc: improvements to debugger.markdown copy
[platform/upstream/nodejs.git] / lib / string_decoder.js
1 'use strict';
2
3 const Buffer = require('buffer').Buffer;
4
5 function assertEncoding(encoding) {
6   // Do not cache `Buffer.isEncoding`, some modules monkey-patch it to support
7   // additional encodings
8   if (encoding && !Buffer.isEncoding(encoding)) {
9     throw new Error('Unknown encoding: ' + encoding);
10   }
11 }
12
13 // StringDecoder provides an interface for efficiently splitting a series of
14 // buffers into a series of JS strings without breaking apart multi-byte
15 // characters. CESU-8 is handled as part of the UTF-8 encoding.
16 //
17 // @TODO Handling all encodings inside a single object makes it very difficult
18 // to reason about this code, so it should be split up in the future.
19 // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
20 // points as used by CESU-8.
21 const StringDecoder = exports.StringDecoder = function(encoding) {
22   this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
23   assertEncoding(encoding);
24   switch (this.encoding) {
25     case 'utf8':
26       // CESU-8 represents each of Surrogate Pair by 3-bytes
27       this.surrogateSize = 3;
28       break;
29     case 'ucs2':
30     case 'utf16le':
31       // UTF-16 represents each of Surrogate Pair by 2-bytes
32       this.surrogateSize = 2;
33       this.detectIncompleteChar = utf16DetectIncompleteChar;
34       break;
35     case 'base64':
36       // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
37       this.surrogateSize = 3;
38       this.detectIncompleteChar = base64DetectIncompleteChar;
39       break;
40     default:
41       this.write = passThroughWrite;
42       return;
43   }
44
45   // Enough space to store all bytes of a single character. UTF-8 needs 4
46   // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
47   this.charBuffer = new Buffer(6);
48   // Number of bytes received for the current incomplete multi-byte character.
49   this.charReceived = 0;
50   // Number of bytes expected for the current incomplete multi-byte character.
51   this.charLength = 0;
52 };
53
54
55 // write decodes the given buffer and returns it as JS string that is
56 // guaranteed to not contain any partial multi-byte characters. Any partial
57 // character found at the end of the buffer is buffered up, and will be
58 // returned when calling write again with the remaining bytes.
59 //
60 // Note: Converting a Buffer containing an orphan surrogate to a String
61 // currently works, but converting a String to a Buffer (via `new Buffer`, or
62 // Buffer#write) will replace incomplete surrogates with the unicode
63 // replacement character. See https://codereview.chromium.org/121173009/ .
64 StringDecoder.prototype.write = function(buffer) {
65   var charStr = '';
66   var buflen = buffer.length;
67   var charBuffer = this.charBuffer;
68   var charLength = this.charLength;
69   var charReceived = this.charReceived;
70   var surrogateSize = this.surrogateSize;
71   var encoding = this.encoding;
72   // if our last write ended with an incomplete multibyte character
73   while (charLength) {
74     // determine how many remaining bytes this buffer has to offer for this char
75     var diff = charLength - charReceived;
76     var available = (buflen >= diff) ? diff : buflen;
77
78     // add the new bytes to the char buffer
79     buffer.copy(charBuffer, charReceived, 0, available);
80     charReceived += available;
81
82     if (charReceived < charLength) {
83       // still not enough chars in this buffer? wait for more ...
84
85       this.charLength = charLength;
86       this.charReceived = charReceived;
87
88       return '';
89     }
90
91     // remove bytes belonging to the current character from the buffer
92     buffer = buffer.slice(available, buflen);
93     buflen = buffer.length;
94
95     // get the character that was split
96     charStr = charBuffer.toString(encoding, 0, charLength);
97
98     // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
99     var charCode = charStr.charCodeAt(charStr.length - 1);
100     if (charCode >= 0xD800 && charCode <= 0xDBFF) {
101       charLength += surrogateSize;
102       charStr = '';
103       continue;
104     }
105     charReceived = charLength = 0;
106
107     // if there are no more bytes in this buffer, just emit our char
108     if (buflen === 0) {
109       this.charLength = charLength;
110       this.charReceived = charReceived;
111
112       return charStr;
113     }
114   }
115
116   // determine and set charLength / charReceived
117   if (this.detectIncompleteChar(buffer))
118     charLength = this.charLength;
119   charReceived = this.charReceived;
120
121   var end = buflen;
122   if (charLength) {
123     // buffer the incomplete character bytes we got
124     buffer.copy(charBuffer, 0, buflen - charReceived, end);
125     end -= charReceived;
126   }
127
128   this.charLength = charLength;
129   charStr += buffer.toString(encoding, 0, end);
130
131   var end = charStr.length - 1;
132   var charCode = charStr.charCodeAt(end);
133   // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
134   if (charCode >= 0xD800 && charCode <= 0xDBFF) {
135     charLength += surrogateSize;
136     charReceived += surrogateSize;
137     charBuffer.copy(charBuffer, surrogateSize, 0, surrogateSize);
138     buffer.copy(charBuffer, 0, 0, surrogateSize);
139
140     this.charLength = charLength;
141     this.charReceived = charReceived;
142
143     return charStr.substring(0, end);
144   }
145
146   // or just emit the charStr
147   return charStr;
148 };
149
150 // detectIncompleteChar determines if there is an incomplete UTF-8 character at
151 // the end of the given buffer. If so, it sets this.charLength to the byte
152 // length that character, and sets this.charReceived to the number of bytes
153 // that are available for this character.
154 StringDecoder.prototype.detectIncompleteChar = function(buffer) {
155   var buflen = buffer.length;
156   // determine how many bytes we have to check at the end of this buffer
157   var i = (buflen >= 3) ? 3 : buflen;
158   var newlen = false;
159
160   // Figure out if one of the last i bytes of our buffer announces an
161   // incomplete char.
162   for (; i > 0; i--) {
163     var c = buffer[buflen - i];
164
165     // See http://en.wikipedia.org/wiki/UTF-8#Description
166
167     // 110XXXXX
168     if (i === 1 && c >> 5 === 0x06) {
169       this.charLength = 2;
170       newlen = true;
171       break;
172     }
173
174     // 1110XXXX
175     if (i <= 2 && c >> 4 === 0x0E) {
176       this.charLength = 3;
177       newlen = true;
178       break;
179     }
180
181     // 11110XXX
182     if (i <= 3 && c >> 3 === 0x1E) {
183       this.charLength = 4;
184       newlen = true;
185       break;
186     }
187   }
188
189   this.charReceived = i;
190
191   return newlen;
192 };
193
194 StringDecoder.prototype.end = function(buffer) {
195   var res = '';
196   if (buffer && buffer.length)
197     res = this.write(buffer);
198
199   var charReceived = this.charReceived;
200   if (charReceived) {
201     var cr = charReceived;
202     var buf = this.charBuffer;
203     var enc = this.encoding;
204     res += buf.toString(enc, 0, cr);
205   }
206
207   return res;
208 };
209
210 function passThroughWrite(buffer) {
211   return buffer.toString(this.encoding);
212 }
213
214 function utf16DetectIncompleteChar(buffer) {
215   var charReceived = this.charReceived = buffer.length % 2;
216   this.charLength = charReceived ? 2 : 0;
217   return true;
218 }
219
220 function base64DetectIncompleteChar(buffer) {
221   var charReceived = this.charReceived = buffer.length % 3;
222   this.charLength = charReceived ? 3 : 0;
223   return true;
224 }