1 var util = require('util')
2 var Stream = require('stream')
3 var StringDecoder = require('string_decoder').StringDecoder
5 module.exports = StringStream
6 module.exports.AlignedStringDecoder = AlignedStringDecoder
8 function StringStream(from, to) {
9 if (!(this instanceof StringStream)) return new StringStream(from, to)
13 if (from == null) from = 'utf8'
15 this.readable = this.writable = true
17 this.toEncoding = (to == null ? from : to)
18 this.fromEncoding = (to == null ? '' : from)
19 this.decoder = new AlignedStringDecoder(this.toEncoding)
21 util.inherits(StringStream, Stream)
23 StringStream.prototype.write = function(data) {
25 var err = new Error('stream not writable')
27 this.emit('error', err)
30 if (this.fromEncoding) {
31 if (Buffer.isBuffer(data)) data = data.toString()
32 data = new Buffer(data, this.fromEncoding)
34 var string = this.decoder.write(data)
35 if (string.length) this.emit('data', string)
39 StringStream.prototype.flush = function() {
40 if (this.decoder.flush) {
41 var string = this.decoder.flush()
42 if (string.length) this.emit('data', string)
46 StringStream.prototype.end = function() {
47 if (!this.writable && !this.readable) return
50 this.writable = this.readable = false
54 StringStream.prototype.destroy = function() {
56 this.writable = this.readable = false
60 StringStream.prototype.pause = function() {
64 StringStream.prototype.resume = function () {
65 if (this.paused) this.emit('drain')
69 function AlignedStringDecoder(encoding) {
70 StringDecoder.call(this, encoding)
72 switch (this.encoding) {
74 this.write = alignedWrite
75 this.alignedBuffer = new Buffer(3)
80 util.inherits(AlignedStringDecoder, StringDecoder)
82 AlignedStringDecoder.prototype.flush = function() {
83 if (!this.alignedBuffer || !this.alignedBytes) return ''
84 var leftover = this.alignedBuffer.toString(this.encoding, 0, this.alignedBytes)
89 function alignedWrite(buffer) {
90 var rem = (this.alignedBytes + buffer.length) % this.alignedBuffer.length
91 if (!rem && !this.alignedBytes) return buffer.toString(this.encoding)
93 var returnBuffer = new Buffer(this.alignedBytes + buffer.length - rem)
95 this.alignedBuffer.copy(returnBuffer, 0, 0, this.alignedBytes)
96 buffer.copy(returnBuffer, this.alignedBytes, 0, buffer.length - rem)
98 buffer.copy(this.alignedBuffer, 0, buffer.length - rem, buffer.length)
99 this.alignedBytes = rem
101 return returnBuffer.toString(this.encoding)