UNPKG

oj

Version:

A unified templating language for the people. Thirsty people.

1 lines 2.29 kB
function assertEncoding(e){if(e&&!Buffer.isEncoding(e))throw new Error("Unknown encoding: "+e)}function passThroughWrite(e){return e.toString(this.encoding)}function utf16DetectIncompleteChar(e){var t=this.charReceived=e.length%2;return this.charLength=t?2:0,t}function base64DetectIncompleteChar(e){var t=this.charReceived=e.length%3;return this.charLength=t?3:0,t}var StringDecoder=exports.StringDecoder=function(e){this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),assertEncoding(e);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6),this.charReceived=0,this.charLength=0};StringDecoder.prototype.write=function(e){var t="",n=0;while(this.charLength){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;e.copy(this.charBuffer,this.charReceived,n,r),this.charReceived+=r-n,n=r;if(this.charReceived<this.charLength)return"";t=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var i=t.charCodeAt(t.length-1);if(i>=55296&&i<=56319){this.charLength+=this.surrogateSize,t="";continue}this.charReceived=this.charLength=0;if(r==e.length)return t;e=e.slice(r,e.length);break}var s=this.detectIncompleteChar(e),o=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-s,o),this.charReceived=s,o-=s),t+=e.toString(this.encoding,0,o);var o=t.length-1,i=t.charCodeAt(o);if(i>=55296&&i<=56319){var u=this.surrogateSize;return this.charLength+=u,this.charReceived+=u,this.charBuffer.copy(this.charBuffer,u,0,u),this.charBuffer.write(t.charAt(t.length-1),this.encoding),t.substring(0,o)}return t},StringDecoder.prototype.detectIncompleteChar=function(e){var t=e.length>=3?3:e.length;for(;t>0;t--){var n=e[e.length-t];if(t==1&&n>>5==6){this.charLength=2;break}if(t<=2&&n>>4==14){this.charLength=3;break}if(t<=3&&n>>3==30){this.charLength=4;break}}return t},StringDecoder.prototype.end=function(e){var t="";e&&e.length&&(t=this.write(e));if(this.charReceived){var n=this.charReceived,r=this.charBuffer,i=this.encoding;t+=r.slice(0,n).toString(i)}return t}