diff options
Diffstat (limited to 'lib/string_decoder.js')
-rw-r--r-- | lib/string_decoder.js | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/lib/string_decoder.js b/lib/string_decoder.js index 879e59064..6b1e30895 100644 --- a/lib/string_decoder.js +++ b/lib/string_decoder.js @@ -19,8 +19,15 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. +function assertEncoding(encoding) { + if (encoding && !Buffer.isEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + var StringDecoder = exports.StringDecoder = function(encoding) { this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); switch (this.encoding) { case 'utf8': // CESU-8 represents each of Surrogate Pair by 3-bytes @@ -32,6 +39,11 @@ var StringDecoder = exports.StringDecoder = function(encoding) { this.surrogateSize = 2; this.detectIncompleteChar = utf16DetectIncompleteChar; break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; default: this.write = passThroughWrite; return; @@ -145,6 +157,21 @@ StringDecoder.prototype.detectIncompleteChar = function(buffer) { return i; }; +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + function passThroughWrite(buffer) { return buffer.toString(this.encoding); } @@ -154,3 +181,9 @@ function utf16DetectIncompleteChar(buffer) { this.charLength = incomplete ? 2 : 0; return incomplete; } + +function base64DetectIncompleteChar(buffer) { + var incomplete = this.charReceived = buffer.length % 3; + this.charLength = incomplete ? 3 : 0; + return incomplete; +} |