UNPKG

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