/*global module, process*/
const Buffer = require('buffer').Buffer;
const Stream = require('stream');
const util = require('util');

function DataStream(data) {
  this.buffer = null;
  this.writable = true;
  this.readable = true;

  // No input
  if (!data) {
    this.buffer = new Buffer(0);
    return this;
  }

  // Stream
  if (typeof data.pipe === 'function') {
    this.buffer = new Buffer(0);
    data.pipe(this);
    return this;
  }

  // Buffer or String
  if (data.length) {
    this.writable = false;
    process.nextTick(function () {
      this.buffer = data;
      this.emit('end', data);
      this.readable = false;
      this.emit('close');
    }.bind(this));
  }
}
util.inherits(DataStream, Stream);

DataStream.prototype.write = function write(data) {
  this.buffer = Buffer.concat([this.buffer, Buffer(data)]);
  this.emit('data', data);
};

DataStream.prototype.end = function end(data) {
  if (data)
    this.write(data);
  this.emit('end', data);
  this.emit('close');
  this.writable = false;
  this.readable = false;
};

module.exports = DataStream;

/*global module, process*/
const Buffer = require('buffer').Buffer;
const Stream = require('stream');
const util = require('util');

function DataStream(data) {
  this.buffer = null;
  this.writable = true;
  this.readable = true;

  // No input
  if (!data) {
    this.buffer = new Buffer(0);
    return this;
  }

  // Stream
  if (typeof data.pipe === 'function') {
    this.buffer = new Buffer(0);
    data.pipe(this);
    return this;
  }

  // Buffer or String
  if (data.length) {
    this.buffer = data;
    this.writable = false;
    process.nextTick(function () {
      this.emit('end', data);
      this.readable = false;
      this.emit('close');
    }.bind(this));
  }
}
util.inherits(DataStream, Stream);

DataStream.prototype.write = function write(data) {
  this.buffer = Buffer.concat([this.buffer, Buffer(data)]);
  this.emit('data', data);
};

DataStream.prototype.end = function end(data) {
  if (data)
    this.write(data);
  this.emit('end', data);
  this.emit('close');
  this.writable = false;
  this.readable = false;
};

module.exports = DataStream;

fix string/buffer being unavailable in streaming interface