Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80522 views
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
22
var Buffer = require('buffer').Buffer;
23
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;
29
}
30
}
31
32
33
function assertEncoding(encoding) {
34
if (encoding && !isBufferEncoding(encoding)) {
35
throw new Error('Unknown encoding: ' + encoding);
36
}
37
}
38
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.
42
//
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) {
51
case 'utf8':
52
// CESU-8 represents each of Surrogate Pair by 3-bytes
53
this.surrogateSize = 3;
54
break;
55
case 'ucs2':
56
case 'utf16le':
57
// UTF-16 represents each of Surrogate Pair by 2-bytes
58
this.surrogateSize = 2;
59
this.detectIncompleteChar = utf16DetectIncompleteChar;
60
break;
61
case 'base64':
62
// Base-64 stores 3 bytes in 4 chars, and pads the remainder.
63
this.surrogateSize = 3;
64
this.detectIncompleteChar = base64DetectIncompleteChar;
65
break;
66
default:
67
this.write = passThroughWrite;
68
return;
69
}
70
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.
77
this.charLength = 0;
78
};
79
80
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.
85
//
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) {
91
var charStr = '';
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 :
97
buffer.length;
98
99
// add the new bytes to the char buffer
100
buffer.copy(this.charBuffer, this.charReceived, 0, available);
101
this.charReceived += available;
102
103
if (this.charReceived < this.charLength) {
104
// still not enough chars in this buffer? wait for more ...
105
return '';
106
}
107
108
// remove bytes belonging to the current character from the buffer
109
buffer = buffer.slice(available, buffer.length);
110
111
// get the character that was split
112
charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
113
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;
118
charStr = '';
119
continue;
120
}
121
this.charReceived = this.charLength = 0;
122
123
// if there are no more bytes in this buffer, just emit our char
124
if (buffer.length === 0) {
125
return charStr;
126
}
127
break;
128
}
129
130
// determine and set charLength / charReceived
131
this.detectIncompleteChar(buffer);
132
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;
138
}
139
140
charStr += buffer.toString(this.encoding, 0, end);
141
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);
152
}
153
154
// or just emit the charStr
155
return charStr;
156
};
157
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;
165
166
// Figure out if one of the last i bytes of our buffer announces an
167
// incomplete char.
168
for (; i > 0; i--) {
169
var c = buffer[buffer.length - i];
170
171
// See http://en.wikipedia.org/wiki/UTF-8#Description
172
173
// 110XXXXX
174
if (i == 1 && c >> 5 == 0x06) {
175
this.charLength = 2;
176
break;
177
}
178
179
// 1110XXXX
180
if (i <= 2 && c >> 4 == 0x0E) {
181
this.charLength = 3;
182
break;
183
}
184
185
// 11110XXX
186
if (i <= 3 && c >> 3 == 0x1E) {
187
this.charLength = 4;
188
break;
189
}
190
}
191
this.charReceived = i;
192
};
193
194
StringDecoder.prototype.end = function(buffer) {
195
var res = '';
196
if (buffer && buffer.length)
197
res = this.write(buffer);
198
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);
204
}
205
206
return res;
207
};
208
209
function passThroughWrite(buffer) {
210
return buffer.toString(this.encoding);
211
}
212
213
function utf16DetectIncompleteChar(buffer) {
214
this.charReceived = buffer.length % 2;
215
this.charLength = this.charReceived ? 2 : 0;
216
}
217
218
function base64DetectIncompleteChar(buffer) {
219
this.charReceived = buffer.length % 3;
220
this.charLength = this.charReceived ? 3 : 0;
221
}
222
223