
var DataView = require('./typedarrays').DataView;
var Thrift = {};

Thrift.MemBuffer = function (buffer) {
    this.queue = [];
    this.buffer = buffer;
    this.offset = 0;
};

Thrift.MemBuffer.prototype.read = function (len) {
    if (this.offset + len > this.buffer.byteLength) throw Error('MemBuffer overrun');
    var view = new DataView(this.buffer, this.offset, len);
    this.offset += len;
    return view;
};

Thrift.MemBuffer.prototype.write = function (bytes) {
    var buf;

    if (bytes instanceof Buffer) {
        buf = bytes;
    } else if (bytes.buf) {
        buf = bytes.buf;
    } else if (bytes.buffer && bytes.buffer.buf) {
        if (bytes.buffer.buf.length != bytes.byteLength) {
            buf = bytes.buffer.buf.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
        } else {
            buf = bytes.buffer.buf;
        }
    } else {
        throw Error('Unsupported type sent to MemBuffer.write. Accepts Buffer, ArrayBuffer polyfill, and DataView polyfill');
    }
    this.queue.push(buf);
};

Thrift.MemBuffer.prototype.clear = function () {
    this.queue = [];
    this.buffer = null;
    this.offset = 0;
};

Thrift.MemBuffer.prototype.flush = function () {
    if (this.buffer) this.queue.unshift(this.buffer);
    this.buffer = Buffer.concat(this.queue);
    this.queue = [];
};

exports.Buffer = Thrift.MemBuffer;
